// ==UserScript==
// @name           KoC Power - Multi
// @version        1.3.9
// @namespace      PDX
// @description    Allround Tool - Kingdom of Camelot - All Lang
// @homepage       http://koc.god-like.org

// @include        *kingdomsofcamelot.com/*main_src.php*
// @include        *kingdomsofcamelot.com/*standAlone.php*
// @include        *kingdomsofcamelot.com/*acceptToken_src.php*
// @include        *kingdomsofcamelot.com/*helpFriend_src.php*
// @include        *apps.facebook.com/kingdomsofcamelot/*
// @include        *facebook.com/connect/uiserver.php*
// @include        *facebook.com/dialog/feed*
// @include        *kabam.com/*

// @resource       en http://koc-power-beta.googlecode.com/svn/trunk/langpacks/en.js
// @resource       de http://koc-power-beta.googlecode.com/svn/trunk/langpacks/de.js
// @resource       SR http://koc-power-beta.googlecode.com/svn/trunk/langpacks/sr.js

// @resource       IMAGES http://koc-power-pdx.googlecode.com/svn/trunk/img/images.js
// @resource       PLUGIN_AVATAR http://koc.god-like.org/multi/beta/plugins/avatars.js
// @resource       PLUGIN_SMILEYS http://koc.god-like.org/multi/beta/plugins/smileys.js

// @icon           http://koc.god-like.org/power/img/kocscripts.png
// ==/UserScript==
var Version = '1.3.9';
var LangpackVersion= '0.5.2 - 09/03/2012';
var MAP_DELAY = 1200;
var DETECT_LEVEL_FS = false;
var URL_CASTLE_BUT = "%2F%2F8X%2F98X%2F973%2F97X%2F77X%2F7633773%2F76X377X3763%2F5q3%2F5qX%2F5pz35q335qX%2F3pz%2F3pT33pz%2F1pT%2F1oz%2F1oT31pT31oz%2FzoT%2Fznv3zoT%2FxXv%2FxXP%2FxWv3xXv3xXP%2FvWv%2FvWP3vWv3vWP%2FtWP%2FtVr%2FtVLmvWv3tWP3tVr3tVL%2FrVL%2FrUrmtWP3rVL3rUrvrVL%2FpUrvrUr%2FpULmrVrmrVL3pUr3pULmpUL3nDrepULWpVLWpUrmnDrFpUK1pVrOnDqcnFKcnEqMnEp7lHN7lGtzlGNrlGtjjEpajFpShFJSe2NChEJKe1o6hDohjDFCc1oZjDEhhDEQjDEAlDEpez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MN3ue93uuN3SLY3uKNXtml3iUogvAN3u%2BV3uIVX%2FE93iIwgvU13fXdXvgVXid4Ai3ogi8Igy5Ygh8Agx9omT4IhU8YBVEQugDwq%2BbNAgRO4CyogirIAi3QAgZ%2B4C54YC1QYASm4ApG4Al%2BYAvuYA%2F%2BYAZWYAzuAhIm4REmYS%2FQAi8IAzEQgzB4YS%2BI4RKeYfv9Ahv%2BAjLIYR0mgxfu4TAggzIoAx8eYiJ%2B4RwO4iDeYSLO4R5mYiPeYR5u4ij%2B4SLugiLGXxrO4hKuXy3eYAxTzuAvpuAJXmAHDmEEroLmfYInaF42doIqUOM1ZmM4nmMGZmMGvuM7hmM3ZmA1xmM%2F5uM5juM1ll8n4F04jmArLoM1YIMyWGMYGIAf6NKxFQVRCAgAOw%3D%3D";
var JSON;if(!JSON){JSON={}}(function(){function str(a,b){var c,d,e,f,g=gap,h,i=b[a];if(i&&typeof i==="object"&&typeof i.toJSON==="function"){i=i.toJSON(a)}if(typeof rep==="function"){i=rep.call(b,a,i)}switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i){return"null"}gap+=indent;h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1){h[c]=str(c,i)||"null"}e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]";gap=g;return e}if(rep&&typeof rep==="object"){f=rep.length;for(c=0;c<f;c+=1){if(typeof rep[c]==="string"){d=rep[c];e=str(d,i);if(e){h.push(quote(d)+(gap?": ":":")+e)}}}}else{for(d in i){if(Object.prototype.hasOwnProperty.call(i,d)){e=str(d,i);if(e){h.push(quote(d)+(gap?": ":":")+e)}}}}e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}";gap=g;return e}}function quote(a){escapable.lastIndex=0;return escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b==="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function f(a){return a<10?"0"+a:a}"use strict";if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(a){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;if(typeof JSON.stringify!=="function"){JSON.stringify=function(a,b,c){var d;gap="";indent="";if(typeof c==="number"){for(d=0;d<c;d+=1){indent+=" "}}else if(typeof c==="string"){indent=c}rep=b;if(b&&typeof b!=="function"&&(typeof b!=="object"||typeof b.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":a})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e==="object"){for(c in e){if(Object.prototype.hasOwnProperty.call(e,c)){d=walk(e,c);if(d!==undefined){e[c]=d}else{delete e[c]}}}}return reviver.call(a,b,e)}var j;text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()
var JSON2 = JSON;
eval(GM_getResourceText( 'IMAGES' ));
var LangOptions = {	culang : 'en',	langpacks : new Object(),};
readLangOptions();
var culang;
if (!langpack) { var langpack = new Object() };
langpack.loaded = false;
eval(GM_getResourceText( LangOptions.culang ));
culang = langpack;
culang.doTranslate=function(text){
	// Replaces alle placeholders in text with corresponding values from culang
	// {%key%}  == culang.key
	
	var pattern=/{%([a-z0-9_$]+)%}/gi;
	var keys=Array();
	while (result = pattern.exec(text)) {
		var key=result[1];
		//GM_log(key);
		var found=false; for(var i=0;i<keys.length;i++){if(keys[i]==key){found=true;break;}}
		if(found) continue;
		keys.push(key);
	}
	var s=text;
	for(var i=0;i<keys.length;i++){
		var key=keys[i];
		if(typeof(culang[key])=="undefined") {
			GM_log("WARNING: Missing translation! 'culang."+key+"' Language: '"+LangOptions.culang+"'");
			continue;
		}
		var exp=new RegExp("{%"+key+"%}","g");
		s=s.replace(exp,culang[key])
	} return s; }
/****************************************************************************
* 		multi language string resources (kocpdx.SR.js) 						*
****************************************************************************/
if(document.body.id == 'mainbody'){
	var SR={languages:["en","de","fr","it","tr","es","se","nl"]};
	for(var iSL=0;iSL<SR.languages.length;iSL++){SR[SR.languages[iSL]]={};}
	SR.getArray=function (entryKey, defLang){
		var tkArray=new Array();
		var tkLangArray2=[defLang].concat(SR.languages);
		for(var tkL=0;tkL<tkLangArray2.length;tkL++){
			var tkLang=tkLangArray2[tkL];
			if(typeof(SR[tkLang])==="undefined") continue;
			for(var tkX=1;;tkX++){
				if(typeof(SR[tkLang][entryKey+"_"+tkX])==="undefined") break;
				tkEntry=SR[tkLang][entryKey+"_"+tkX];
				tkExist=false;
				for(var tkAi=0;tkAi<tkArray.length;tkAi++){
					if(tkArray[tkAi]===tkEntry){tkExist=true;break;}
				}
				if(tkExist) continue;
				tkArray.push(tkEntry);
			}
		} return tkArray; 
		};
	try{eval(GM_getResourceText('SR'));SR.loaded=true;}
	catch(ex){
		GM_log("ERROR: loading kocpdx.SR.js"+"\n"+ex);
		srErrDiv=document.createElement("div");
		srErrDiv.innerHTML="ERROR loading kocpdx.SR.js!";
		srErrDiv.setAttribute("style","background:yellow");
		document.body.insertBefore(srErrDiv, document.body.firstChild);
	}
	GM_log("String resources loaded: "+(SR.loaded==true));
	
	// define 'en' fallback
	for (var srEntry in SR.en){
		if(srEntry.match(/_[0-9]+$/)) continue; // skip "array" entries "item_1,item_2"
		// GM_log("SR.en."+srEntry+"="+"'"+SR.de[srEntry]+"';");
		if(typeof(SR.de[srEntry])==="undefined")SR.de[srEntry]=SR.en[srEntry];
		if(typeof(SR.fr[srEntry])==="undefined")SR.fr[srEntry]=SR.en[srEntry];
		if(typeof(SR.it[srEntry])==="undefined")SR.it[srEntry]=SR.en[srEntry];
		if(typeof(SR.tr[srEntry])==="undefined")SR.tr[srEntry]=SR.en[srEntry];
		if(typeof(SR.es[srEntry])==="undefined")SR.es[srEntry]=SR.en[srEntry];
		if(typeof(SR.se[srEntry])==="undefined")SR.se[srEntry]=SR.en[srEntry];
		if(typeof(SR.nl[srEntry])==="undefined")SR.nl[srEntry]=SR.en[srEntry];
	}
}
//#endregion multi language string resources (kocpdx.SR.js) 
var butON='<img align=absmiddle src="%3D" alt="ON">';
var butOFF='<img align=absmiddle src="%3D%3D" alt="OFF">';
var ResetAll=false,deleting=false;
var sitesupport="http://beworld.perso.sfr.fr/bao/";
var URL_PROVINCE_MAP = "%2F%2F%2F%2Ff%2F%2F%2Fv%2F8%2Ff3%2F%2Ff39%2Ff37%2F%2F%2Fpe%2F39%2F%2F%2FnO%2F37%2F%2F%2FlPf%2FnPf%2FlPHv9%2B%2Fv7%2F%2F3lO%2Fv5ubv7%2Ff3lPf3jO%2Fm7%2B%2F3jO%2F0lPfvlObm7%2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suUAAA5kDgO6lOcWjZdSMFSi8ZADr2CtxWK9GGZrVwBoIZYYKy5QWbMmHQSyZm0MQw0rcRWEydfvXJMHIXYloMaaOEgitYrj81LwRQ2swlAMcUmcKxspMWuOTJEDri0UHYr7ybBEqIQdP%2B%2FUALn13NcVZ8dW6iDpRNy2lQbgAFsvb6Ua5OotLvwigdwMlSNvTvH5xOjIYR4nTvs4dejLAUzXjh289t3bK3pvPV43d%2FTUr1OsPfG9c%2FXzv5uMDxP49%2Fu1AwIAOw%3D%3D";
var provMapCoords = {imgWidth:710, imgHeight:708, mapWidth:670, mapHeight:670, leftMargin:31, topMargin:19};  
var DEFAULT_ALERT_SOUND_URL = 'http://www.universal-soundbank.com/mp3/sounds/261.mp3';
var SWF_PLAYER_URL = sitesupport+'miniplayer.swf';
var Options={NewTab:true,NewTabURL:sitesupport,NewTabName:"BAO",currentTab:null,currentTab2:"Overview1",reapprointerval:0,TSSrchFilter:0,BOTransparence:true,includeMarching:false,EnableFormation:false,showTroops:true,showPop:false,Smiley:true,showRes:true,checktournoi:false,SelQG:null,showProduction:true,showDefense:false,encRemaining:true,pbEveryEnable:true,pbEveryMins:60,pbChatOnRight:false,pbWideMap:false,pbKillFairie:true,maxIdlePop:true,ChatLearder:true,voirRaid:false,WhisperOn:true,gmtClock:false,AttaqueOn:false,EclaireurOn:false,srcSortBy:"level",EnableRefrechRapport:false,srcMinLevel:1,srcMaxLevel:10,srcTypeSelect:1,srcaDist:0,srcDist:20,Xrenfort:0,srcScoutAmt:1,PageReport:1,Yrenfort:0,icon_chat:false,URLicon:"http://www.france-lol.fr/francelol.tools/images/ip_points.png",filPuissance:0,filPuissanceMax:1e6,wildType:1,citySrchFilter:0,fixPageNav:true,mistedOnly:false,hostileOnly:false,fixTower:true,enhanceARpts:true,allowAlterAR:true,enableCheckTournoi:true,HauteurBoite:700,pbWinIsOpen:false,boTrackOpen:true,ptWin2IsOpen:false,ptWinDrag:true,ptWinPos:{},ptWin2Pos:{},enableFoodWarn:true,enableFoodWarnTchat:false,EnableReduireUnit:true,foodWarnHours:24,chatEnhance:true,fixKnightSelect:true,attackCityPicker:true,mapCoordsTop:true,dispBattleRounds:true,reportDeleteButton:true,arPageFrom:1,arPageTo:2,rptType:"alliance",rptAuto:false,alertSound:{enabled:true,soundUrl:DEFAULT_ALERT_SOUND_URL,repeat:true,playLength:20,repeatDelay:.5,volume:100,alarmActive:false,expireTime:0},alertConfig:{aChat:true,raid:false,aPrefix:"**** Je suis attaque !!! **",scouting:true,wilds:true,defence:true,minTroops:1,minTroops2:1,embassy:false,empennage:true,marechal:true,defBoost:true,mytroops:false,food:false,defense:true,MonQG:true,hq:"",sendEmail:false,emailAddress:"",token:"",sendasWhisper:false,sendtoAlly:true,showAttack:false,},URLson1:"http://www.universal-soundbank.com/mp3/sounds/684.mp3",URLson2:"http://www.universal-soundbank.com/mp3/sounds/217.mp3",URLson4:"http://www.universal-soundbank.com/mp3/sounds/2376.mp3",AttackHorloge:"21:00:00",AttackGoHorloge:null,AttackOnOff:false,AttackUnits:{},AttackFav:{0:{0:"200K miliciens",1:0,2:2e5,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},1:{0:"200K dada",1:0,2:0,3:0,4:0,5:0,6:0,7:2e5,8:0,9:0,10:0,11:0,12:0,13:0}},AttackFromCity:0,AttackCibleX:0,AttackCibleY:0,AttackKnight:0,TournoiLigne:25,AttackFSUnits:{1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},5:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},6:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},7:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},8:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},9:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},10:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0}},DeleteMsg:false,DeleteMsgs0:false,DeleteMsgs1:false,DeleteMsgs2:false,DeleteMsgs3:false,DeleteTimerMinute:5,giftDomains:{valid:false,list:{}},giftDelete:"e",HelpRequest:true,ChatRules:false,DeleteRequest:true,MapShowExtra:false,transportinterval:60,minwagons:1e3,lasttransport:0,reassigninterval:60,lastreassign:0,RaidRunning:true,RaidReset:0,MsgInterval:1,foodreport:false,Foodstatus:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},LastReport:0,Creststatus:{1101:0,1102:0,1103:0,1104:0,1105:0,1106:0,1107:0,1108:0,1109:0,1110:0,1111:0,1112:0,1113:0,1114:0,1115:0},CrestMsgInterval:24,crestreport:false,Crest1Count:0,Crest2Count:0,CrestLevel:0,CrestType:0,CrestMsgInterval:24,LastCrestReport:0,spamconfig:{aspam:false,spamvert:"Nous recrutons, rejoignez-nous",spammins:"10",atime:2,spamstate:"a"},
BOPreset:{1:"Attaque (exemple)",2:"Defense (exemple)",3:"",4:"",5:"",6:"",7:"",8:""},EffetRouge:0,AllEffet:false,salvageconfig:{running:false,mins:60,typeselect:0,},pbGoldHappy:95,pbGoldEnable:false,enhanceViewMembers:true};
var Colors ={ChatLeaders:'#C8C8C8',ChatVC:'#81EE81',ChatChancy:'#F8A151',ChatAtt:'#FF7D7D',ChatEcl:'#FFDD7D',ChatGlo:'#F9AAAA',};
var CrestOptions={Running:false,CrestCity:0,RoundOne:true,RoundTwo:true,lastRoundTwo:0,X:0,Y:0,R1MM:0,R1Scout:0,R1Ball:0,R1Cat:0,R2MM:0,R2Scout:0,R2Pike:0,R2Sword:0,R2Arch:0,R2Ball:0,R2Ram:0,R2Cat:0,R2Wag:0,Crest1City:0,RoundThree:true,RoundFour:true,lastRoundFour:0,CX:0,CY:0,R3MM:0,R3Scout:0,R3Ball:0,R3Cat:0,R4MM:0,R4Scout:0,R4Pike:0,R4Sword:0,R4Arch:0,R4Ball:0,R4Ram:0,R4Cat:0,R4Wag:0}
var AttackOptions={LastReport:0,MsgEnabled:true,MsgInterval:60,Method:"distance",SendInterval:8,MaxDistance:50,RallyClip:0,Running:false,BarbsFailedKnight:0,BarbsFailedRP:0,BarbsFailedTraffic:0,BarbsFailedVaria:0,BarbsFailedMarais:0,BarbsFailedBog:0,BarbsTried:0,DeleteMsg:true,DeleteMsgs0:false,Foodstatus:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},MsgLevel:{1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true,9:true,10:true},BarbsDone:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},BarbNumber:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},Levels:{1:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},2:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},3:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},4:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},5:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},6:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},7:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},8:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false}},Troops:{1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},5:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},6:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},7:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},8:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},9:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0},10:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0}},MinDistance:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0},Distance:{1:750,2:750,3:750,4:750,5:750,6:750,7:750,8:750,9:750,10:750},Update:{1:[0,0],2:[0,0],3:[0,0],4:[0,0],5:[0,0],6:[0,0],7:[0,0],8:[0,0]},UpdateEnabled:true,UpdateInterval:30,stopsearch:1,knightselector:0}
var TrainOptions={Running:false,list:{},listactif:{},listlabour:{},timelauch:60,unitemin:{},unitemax:{},listboost:{},UnitMixValue:100,Workers:{1:100,2:100,3:100,4:100,5:100,6:100,7:100,8:100},Keep:{1:{Food:0,Wood:0,Stone:0,Ore:0},2:{Food:0,Wood:0,Stone:0,Ore:0},3:{Food:0,Wood:0,Stone:0,Ore:0},4:{Food:0,Wood:0,Stone:0,Ore:0},5:{Food:0,Wood:0,Stone:0,Ore:0},6:{Food:0,Wood:0,Stone:0,Ore:0},7:{Food:0,Wood:0,Stone:0,Ore:0},8:{Food:0,Wood:0,Stone:0,Ore:0}},Resource:{1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true},CraftingRunning:false,CraftingActif:{221:false,3e3:false,3001:false,3002:false,3003:false,3004:false,3005:false,3006:false,3007:false,3008:false,3009:false,3010:false,3011:false,},CraftingNb:{221:0,3e3:0,3001:0,3002:0,3003:0,3004:0,3005:0,3006:0,3007:0,3008:0,3009:0,3010:0,3011:0,},doTraps:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},doCalrops:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},doSpikes:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},doXbows:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},doTrebu:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},troopType:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},keepFood:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},keepWood:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},keepStone:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},keepOre:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0}}
var GlobalOptions={pbWatchdog:true,pbWideScreen:true,pbWideScreenStyle:"normal",autoPublishGamePopups:false,}
var CombatOptions={research:[{tch8:0,tch9:0,tch13:0,tch15:0},{tch8:0,tch9:0,tch13:0,tch15:0}],knt:[50,50],guardian:[["wood",0],["ore",0]],ratio:[{unt1:{},unt2:{},unt3:{},unt4:{},unt5:{},unt6:{},unt7:{},unt8:{},unt9:{},unt10:{},unt11:{},unt12:{}},{unt1:{},unt2:{},unt3:{},unt4:{},unt5:{},unt6:{},unt7:{},unt8:{},unt9:{},unt10:{},unt11:{},unt12:{}}]}
var avatars = {};
eval(GM_getResourceText("PLUGIN_AVATAR"));
var Smileys = {};
eval(GM_getResourceText("PLUGIN_SMILEYS"));
var nHtml={FindByXPath:function(a,b,c){if(!c){c=XPathResult.FIRST_ORDERED_NODE_TYPE}try{var d=document.evaluate(b,a,null,c,null)}catch(e){GM_log("bad xpath:"+b)}if(c==XPathResult.FIRST_ORDERED_NODE_TYPE){if(d&&d.singleNodeValue){return d.singleNodeValue}}else{if(d){return d}}return null},ClickWin:function(a,b,c){var d=a.document.createEvent("MouseEvents");d.initMouseEvent(c,true,true,a,0,0,0,0,0,false,false,false,false,0,null);return!b.dispatchEvent(d)},Click:function(a){return this.ClickWin(window,a,"click")},ClickTimeout:function(a,b){window.setTimeout(function(){return nHtml.ClickWin(window,a,"click")},b+Math.floor(Math.random()*500))},SetSelect:function(a,b){for(var c=0;c<a.options.length;c++){if(b==a.options[c].value){a.options[c].selected=true;return true}}return false}}
function ById(id) {return document.getElementById(id);}
if (document.URL.search(/kingdomsofcamelot.com\/fb\/e2\/src\/helpFriend_src.php/i) >= 0){ helpFriends (); return true;}
readGlobalOptions ();
if (document.URL.search(/kabam.com\/kingdoms-of-camelot\/play/i) >= 0 || document.URL.search(/kingdomsofcamelot\.com\/fb\/.*?\/standAlone\.php/i) >= 0){  kabamStandAlone ();  return;}
if (document.URL.search(/apps.facebook.com\/kingdomsofcamelot/i) >= 0){  facebookInstance ();  return;}
if (document.URL.search(/facebook.com\/dialog\/feed/i) >= 0){ HandlePublishPopup ();  return;}
if (document.URL.search(/kingdomsofcamelot.com\/fb\/e2\/standAlone/i) >= 0){
  var gameIframe=document.body;
  for(i=0; i<gameIframe.childNodes.length; i++){
          if (gameIframe.childNodes[i].tagName=="DIV") {

          if (gameIframe.childNodes[i].childNodes[0]) gameIframe.childNodes[i].childNodes[0].style.width="100%"
        }
   }
  return;
}
if (document.URL.search(/kingdomsofcamelot.com\/fb\/e2\/src\/main/i) >= 0){  kocWideScreen ();}
function helpFriends(){function a(){var b=ById("claimhelpform");if(!b){setTimeout(a,1e3)}b.submit()}a()}

function readGlobalOptions (){ GlobalOptions = JSON2.parse (GM_getValue ('Options_??', '{}'));}
function kocWideScreen(){
  var fois=0;
  function setWideFb (){
	var kocFrame = parent.document.getElementById('kocIframes1');
	if (!kocFrame){
	  setTimeout (setWideFb, 1000);
	  return;
	}
	kocFrame.style.width = '100%';
	var style = document.createElement('style')
	style.innerHTML = 'body {margin:0; width:100%; !important;}';
	kocFrame.parentNode.appendChild(style);
	

  }
  function test() {
  	var alla = ById('kocinitloading');
  	if (alla) {
  	 if (alla.style.display!="none") {
  	  fois++;
  	  if (fois>23)  reloadKOC();
  	  setTimeout (test, 2500);
  	  return;
  	 }
	}
  
  }
  if(document.URL.match(/standalone=0/i)){
	  kocWatchdog ();
	  test();
	  if (GlobalOptions.pbWideScreen)
			setWideFb();
  }
}
function kabamStandAlone(){function a(){var b=document.getElementsByTagName("IFRAME");if(!b){setTimeout(a,1e3);return}for(var c=0;c<b.length;c++){if(b[c].src.match(/kingdomsofcamelot\.com\/fb\/.*?\/standAlone\.php/i)){b[c].style.width="100%";ById("content").style.width="100%"}if(b[c].src.match(/kingdomsofcamelot\.com\/fb\/.*?\/main_src\.php/i)){b[c].style.width="100%"}}}if(GlobalOptions.pbWideScreen)a()}
function facebookInstance(){function a(){var b=ById("iframe_canvas");if(!b){setTimeout(a,1e3);return}b.style.width="100%";while((b=b.parentNode)!=null)if(b.tagName=="DIV")b.style.width="100%";ById("globalContainer").style.left="0px";try{ById("rightCol").parentNode.removeChild(ById("rightCol"));ById("leftColContainer").parentNode.removeChild(ById("leftColContainer"))}catch(c){}
var c=ById("mainContainer");
if(c){if(GlobalOptions.pbWideScreenStyle=="normal")
c.parentNode.style.minWidth="100%";
	var pied = document.getElementById('pagelet_canvas_footer_content');
	if(pied) { pied.parentNode.removeChild(pied); }
if(GlobalOptions.pbWideScreenStyle=="wide")c.parentNode.style.width="1520px";if(GlobalOptions.pbWideScreenStyle=="ultra")c.parentNode.style.width="2000px";for(i=0;i<c.childNodes.length;i++){if(c.childNodes[i].id=="contentCol"){c.childNodes[i].style.margin="0px";c.childNodes[i].style.paddingTop="0px";break}}}var c=ById("pageHead");if(c){c.style.width="80%";c.style.margin="0 10%"}var c=ById("bottomContent");if(c){c.style.padding="0px 0px 12px 0px"}}facebookWatchdog();if(GlobalOptions.pbWideScreen)a()}
function HandlePublishPopup() {
 if(GlobalOptions.autoPublishGamePopups){
		var FBInputForm = document.getElementById('uiserver_form');
		if(FBInputForm){
			var channel_input = nHtml.FindByXPath(FBInputForm,".//input[contains(@name,'channel')]");
			
			if(channel_input){
				var current_channel_url = channel_input.value;
					var publish_button = nHtml.FindByXPath(FBInputForm,".//input[@type='submit' and contains(@name,'publish')]");
					
					var test =ById("feedform_user_message");

					
					if(publish_button && test){ 
						setTimeout(function() {
						 nHtml.Click(publish_button);
						},2500);
					}
			}		
		}
    setTimeout(HandlePublishPopup, 5000);
   }
 
}
function facebookWatchdog(){function b(){try{if(ById("app_content_130402594779")==null){logit("KOC NOT FOUND!");KOCnotFound(5*60)}}catch(a){logit("KOC NOT FOUND!");KOCnotFound(4*60)}}var a=5e4;if(!GlobalOptions.pbWatchdog)return;setTimeout(b,a)}
function kocWatchdog(){function b(){if(ById("mod_maparea")==null){logit("KOC not loaded");KOCnotFound(20)}}var a=1e4;if(!GlobalOptions.pbWatchdog)return;setTimeout(b,a)}
readOptions();
var Cities = {};
var Seed = unsafeWindow.seed;
var uW = unsafeWindow;
var Tabs = {};
var my = {};
var myBO = {};
var researchLevels = [];
var crestname = {};
var CPopUpTopClass = 'pbPopTop';
var mainPop, mainPop2;
var ResetColors = false;
var Tabs2=[["Attaque",uW.g_js_strings.commonstr.attack],["Overview","R&eacute;serves"],["Crest",uW.g_js_strings.commonstr.crest],["Stock",uW.g_js_strings.commonstr.inventory],["Info","Info"],["Alliance",uW.g_js_strings.commonstr.alliance],["Tournoi",uW.g_js_strings.commonstr.tournament],["Gifts",uW.g_js_strings.commonstr.gift],["Resources",uW.g_js_strings.commonstr.resources],["Combat","Combat"],["Spam","Spam"],["Trone","Trone"],["Test","Test"],["ActionLog","Logs"]]
var BOStartupTimer = null;
ptStartupErrorTimer = null;
var currentName2 = 'Attaque';
var myServerId = null;
function getServerId(){if(myServerId==null){var a=/^[a-zA-Z]+([0-9]+)\./.exec(document.location.hostname);if(a)myServerId=a[1];else myServerId="??"}return myServerId}
function ptStartup (){
  clearTimeout (BOStartupTimer);
  if (unsafeWindow.BOLoaded)
    return;   
  var metc = getClientCoords(ById('main_engagement_tabs'));
  if (metc.width==null || metc.width==0){
    BOStartupTimer = setTimeout (ptStartup, 1000);
    return;
  }
  unsafeWindow.BOLoaded = Version;
  readOptions();
  readColors();  
  Seed = unsafeWindow.seed;
GM_addStyle ('.xtab {padding-right: 5px; border:none; background:none; white-space:nowrap;}\
.tourny_list_table { padding: 10px; -moz-border-radius:5px; border:2px solid #000000; }\
    .hostile td { background:crimson; }.amicale td{background:lightblue; }.allie td{background:royalblue; }\
    .neutre td { background:lightgreen; }.unaligned td { background:gold; }\
    .xtabBR {padding-right: 5px; border:none; background:none;}\
    .boAide {height:20px;font-size:9px;font-weight:bold;}\
    div.ptDiv {background-color:none;}\
    table.ptTab tr td {border:none; background:none; white-space:nowrap;}\
    table.ptTabPad tr td {border:none; background:none; white-space:nowrap; padding: 2px 4px 2px 8px;}\
    table.ptTabBR tr td {border:none; background:none;}\
    table.pbTabLined tr td {border:1px none none solid none; padding: 2px 5px; white-space:nowrap;}\
    table.ptTabPad tr td.ptentry {background-color:#ffeecc; padding-left: 8px;}\
    table.ptTabOverview tr td {border-left:1px solid #ccc; white-space:nowrap; padding: 1px;   font-size:11px;}\
    table.ptNoPad tr td {border:none; background:none; white-space:nowrap; padding:0px}\
    .ptOddrow {background-color:#eee}\
    .boStat {border: 0.5px solid #ffffff; -moz-border-radius:2px; -moz-box-shadow: inset 0px 0px 3px #ffffff; font-weight:bold; padding-top:2px; padding-bottom:2px; text-align:center; color:#ffffff;	background-color:#262}\
    .ptStatLight {color:#ddd}\
    .ptentry {padding: 7px; border:1px solid; border-color:#000000; background-color:#ffeecc; white-space:nowrap;}\
    .ptErrText {font-weight:bold; color:#600000}\
    .castleBut {outline:0px; margin-left:0px; margin-right:0px; width:24px; height:26px; font-size:12px; font-weight:bold;}\
    .castleBut:hover {border-size:3px; border-color:#000;}\
    button::-moz-focus-inner, input[type="submit"]::-moz-focus-inner { border: none; }\
    .ptChatWhisper {}\
    .ptChatAttack {color: #000; font-weight:bold; background-color: '+Colors.ChatAtt+'; }\
    .ptChatScout {color: #000; font-weight:bold; background-color: '+Colors.ChatEcl+'; }\
    .ptChatAlliance {}\
    .ptChatGlobal {background-color: #fdd}\
    .ptChatIcon {border: 0px inset black}\
    .ptChatScripter {font-weight:bold;}\
    .ptChatCHAN {color:#000; background-color:'+Colors.ChatChancy+';}\
    .ptChatVICE {color:#000; background-color:'+Colors.ChatVC+';}\
    .ptChatOFFI {color:#000; background-color:'+Colors.ChatLeaders+';}\
    input.BODefButOn {cursor:pointer; border:1px solid black; background-color:red;}\
    input.BODefButOff {cursor:pointer; border:1px solid black; background-color:#0a0;}\
    span.whiteOnRed {padding-left:3px; padding-right:3px; background-color:#700; color:white; font-weight:bold}\
    span.boldRed {color:#800; font-weight:bold}\
    span.oohfancy {color:#0000; font-weight:bold;text-shadow: 1px 1px 1px #AAA; font-variant:small-caps; text-align:center}\
    span.oohfancyi {color:#0000; font-style:italic;text-shadow: 1px 1px 1px #AAA; font-variant:small-caps; text-align:center}\
    .emoicon {width:19px !important;height:19px !important;float:none !important;}\
    .castleButNon {background-image:url("'+ URL_CASTLE_BUT +'")}\
    .castleButSel {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}\
    span.boldDarkRed {color:#600; font-weight:bold}\
    a.ptButton20 {color:#ffff80}\
    input.bopbSubtab {cursor:pointer; width:10em; margin-right:15px;}\
    input.bopbSubtabSel {background-color:#444444; color:white; font-weight:bold; cursor:none !important}\
    matTab {}\
   .matTabNotSel { padding:0 0 0 20px;  color : #2F230E; font: bold 11px Georgia; white-space: nowrap; cursur:pointer; padding:0px;height: 17px; }\
   .matTabNotSel span { color : #2F230E; background: url("http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/nav/tab_unselected.png") no-repeat scroll left 0 transparent; display: inline-block;  height: 16px;    padding: 1px 2px 0 7px;    text-decoration: none;   }\
   .BOTabSel { color : #2F230E; font: bold 11px Georgia; white-space: nowrap; cursur:pointer; padding:0 0px 0 0;height: 17px;   }\
   .BOTabSel span { color : #2F230E; background: url("http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/nav/tab_selected.png") no-repeat scroll left top transparent; display: inline-block; width:74px;    height: 16px;    padding: 1px 2px 0 7px;    text-decoration: none;   }\
   .BOTabNotSel { padding:0 0 0 20px;  color : #2F230E; font: bold 11px Georgia; white-space: nowrap; cursur:pointer; padding:0px;height: 17px; }\
   .BOTabNotSel span { color : #2F230E; background: url("http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/nav/tab_unselected.png") no-repeat scroll left 0 transparent; display: inline-block; width:74px;   height: 16px;    padding: 1px 2px 0 7px;    text-decoration: none;   }\
   .matTabSel { color : #2F230E; font: bold 11px Georgia; white-space: nowrap; cursur:pointer; padding:0 0px 0 0;height: 17px;   }\
   .matTabSel span { color : #2F230E; background: url("http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/nav/tab_selected.png") no-repeat scroll left top transparent; display: inline-block;  height: 16px;    padding: 1px 2px 0 7px;    text-decoration: none;   }\
   tr.BOCPopupTop td { border:none; height: 15px;  padding:0px; }\
   .BOptretry_top { background-color:#a00; color:#fff; border:none; height: 21px; padding:0px; }\
   input.ptButCancel {background-color:#a00; font-weight:bold; color:#fff}\
   .BOCPopup .BOCPopMain {  opacity:0.9;-moz-box-shadow:inset 0px 0px 20px #006000; -moz-border-radius:3px; border:1px solid #141516; padding:3px; }\
   .idp_CPopup .idp2_CPopup { opacity:0.9; }');
    
  readTrainingOptions();readCrestOptions();readAttackOptions();setCities();readCombatOptions();
  if (Options.ptWinPos==null || Options.ptWinPos.x==null|| Options.ptWinPos.x=='' || isNaN(Options.ptWinPos.x)){
    var c = getClientCoords (ById('main_engagement_tabs'));
    Options.ptWinPos.x = c.x+4;
    Options.ptWinPos.y = c.y+c.height;
    saveOptions ();
  }
  if (Options.ptWin2Pos==null || Options.ptWin2Pos.x==null|| Options.ptWin2Pos.x=='' || isNaN(Options.ptWin2Pos.x)){
      var c = getClientCoords (ById('main_engagement_tabs'));
      Options.ptWin2Pos.x = c.x+4;
      Options.ptWin2Pos.y = c.y+c.height;
      saveOptions ();
  }
  if(!GlobalOptions.pbWideScreen && Options.ptWinPos.x > 700){
    var c = getClientCoords (ById('main_engagement_tabs'));
    Options.ptWinPos.x = c.x+4;
    saveOptions ();
  }
  var hauteur=parseIntNan(Options.HauteurBoite) + 20;
  mainPop = new CPopup ('idp1', Options.ptWinPos.x, Options.ptWinPos.y, 800, hauteur, Options.ptWinDrag, 
     function (){
        tabManager.hideTab();
        Options.pbWinIsOpen=false;
        saveOptions()
  });
  var mainDiv = mainPop.getMainDiv();
  mainPop.getTopDiv().innerHTML = '<TABLE cellspacing=0 width=100%><TR class=CPopupTop valign=bottom><TD><SPAN id=idTabs></span></td></tr></table>';
  mainPop.autoWidth(true); 
  
  AddMainTabLink("POWER", eventHideShow, mouseMainTab); 
  tabManager.init (mainPop.getMainDiv());
  TowerAlerts.init();
  AllianceReports.init ();
  messageNav.init();


  RefreshEvery.init();  
  ChatStuff.init ();

  battleReports.init ();
  AttackDialog.init(); 
  ChatPane.init();
  CoordBox.init();
  setTimeout(function() { 
     DeleteReports.init(); 
     exportToKOCattackBO.init();
     SpamEvery.init (); 
     CollectGold.init(); 
     FairieKiller.init (Options.pbKillFairie);
     FoodAlerts.init(); 
     SalvageAuto.init (); 
  },60000); // on attends 60 sec avant le lancement de certains fonction
  if (Options.pbWinIsOpen){
    mainPop.show (true);
    tabManager.showTab();
  }
  window.addEventListener('unload', onUnload, false);
  TowerAlerts.setPostToChatOptions(Options.alertConfig);
  AddMainTabLink2("Stats", eventHideShow2, mouseMainTab2);
  WideScreen.init ();
  WideScreen.setChatOnRight (Options.pbChatOnRight);
  WideScreen.useWideMap (Options.pbWideMap);
  gmtClock.init();
  if (Options.checktournoi) {
   var params=unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);params.format=2;params.tournyPos=0;new AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/getLeaderboard.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,onSuccess:function(transport){var rslt=eval("("+transport.responseText+")");if(rslt.ok){if(rslt.data){ById("ptBoite2").innerHTML='<span style="color: #f66"> <blink>TOURNOI</blink> </span>';Options.enableCheckTournoi=false;saveOptions()}else{Options.enableCheckTournoi=true}}else{Options.enableCheckTournoi=true}}})
   CheckTournoi.init();
  }
  if (Options.currentTab2) {
      currentName2 = Options.currentTab2;
      if (currentName2=='Overview1')  currentName2 = 'Attaque';
      if (currentName2=='map')  currentName2 = 'Attaque';
      if (currentName2=='build')  currentName2 = 'Attaque';
      if (currentName2=='autoFormation') currentName2 = 'Attaque';
     } else {
      currentName2 = 'Attaque';
     }
     mainPop2 = new CPopup ('idp2', Options.ptWin2Pos.x, Options.ptWin2Pos.y, 779,350, true, 
           function (){
              if (myBO[currentName2]==undefined) {
	          currentName2 = 'Attaque';
    }
             myBO[currentName2].hide();
             Options.ptWin2IsOpen=false; 
             saveOptions();
         });
     var mainDiv2 = mainPop2.getMainDiv();
     mainPop2.getTopDiv().innerHTML = '<TABLE cellspacing=0 width=100%><TR class=CPopupTop valign=bottom><TD><SPAN id=idTabs2></span></td></tr><tr><td><span id=idTabs3></span></tr></table>';
     mainPop2.autoHeight (true); 
     mainPop2.autoWidth(true); 
     
     var eTabs2 = ById('idTabs2');
    for (k=0; k<Tabs2.length; k++){
        var a=document.createElement('a');
        
        a.id = 'ab'+ Tabs2[k][0];
        a.innerHTML='<span id="spp'+ Tabs2[k][0] +'" class="matTab">'+ Tabs2[k][1] +'</span>';
        if (k==9) {
         var eTabs2 = ById('idTabs3');
         eTabs2.innerHTML+="</tr><tr><td>";
        } 
        eTabs2.appendChild(a);
        a.addEventListener('click', clickedTab2, false);
        myBO[Tabs2[k][0]].init();
        cont = myBO[Tabs2[k][0]].getContent();
        if (Tabs2[k][0]==currentName2) {
         cont.style.display = 'block';
         a.className='matTabSel';
        }else {
         cont.style.display = 'none';
         a.className='matTabNotSel';
        }
        mainDiv2.appendChild(cont);
 } 
   if (Options.ptWin2IsOpen){
    mainPop2.show (true);
    if (myBO[currentName2]==undefined) {
     currentName2 = 'Attaque';
    }
    myBO[currentName2].show();
  }

  if (Options.SelQG) {
    if (parseIntNan(Options.alertConfig.hq)>0) {
     setTimeout(function() {  
        var idx=Cities.byID[Options.alertConfig.hq].idx;
        unsafeWindow.citysel_click(ById('citysel_'+ (idx+1)));      
     },1000);
    }
  }
  
  if (Options.MapShowExtra) setInterval (DrawLevelIcons,2000);
}
function onUnload(){Options.ptWinPos=mainPop.getLocation();Options.ptWin2Pos=mainPop2.getLocation();saveOptions();if(!ResetColors)saveColors()}
function getAlliance (aid){
  if (Seed.allianceDiplomacies==null || Seed.allianceDiplomacies.allianceName==null)
    return ['neutre', 0, 'None'];
  else if (Seed.allianceDiplomacies.friendly && Seed.allianceDiplomacies.friendly['a'+aid] != null)
      return ['amicale',Seed.allianceDiplomacies.allianceId, Seed.allianceDiplomacies.allianceName];
  else if (Seed.allianceDiplomacies.hostile && Seed.allianceDiplomacies.hostile['a'+aid] != null)
      return ['hostile',Seed.allianceDiplomacies.hostile['a'+aid].allianceId, Seed.allianceDiplomacies.hostile['a'+aid].allianceName]; 
}
var CoordBox={init:function(){var a=CoordBox;a.boxDiv=searchDOM(ById("maparea_map"),'node.className=="mod_coord"',3,false);a.setEnable(Options.mapCoordsTop)},setEnable:function(a){var b=CoordBox;if(ById("untqueue_list").style.display!="none")unsafeWindow.cm.MarchProgressBar.toggle();
if(ById("hudTopContainer")) {
 //ById("hudTopContainer").style.display="none";
 ById("hudTopContainer").innerHTML='<a onmouseover="showTooltip(&quot;Choisis un cadeau GRATUIT à envoyer à tes amis !&quot;,this,event,&quot;maparea_fields&quot;);" onmouseout="removeTooltip();" target="_blank" href="http://apps.facebook.com/kingdomsofcamelot/?page=choosegift"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/gift_icon_50.png"></a>';
}
//if(ById("hudBottomContainer"))ById("hudBottomContainer").style.display="none";
//if(ById("hudThirdContainer"))ById("hudThirdContainer").style.display="none";
if(ById("sharethis_icon"))ById("sharethis_icon").style.display="none";
if(b.boxDiv==null)return;if(a){b.boxDiv.style.zIndex="100000";b.boxDiv.style.left="5px";if(Options.pbChatOnRight){b.boxDiv.style.top="470px"}}else{b.boxDiv.style.zIndex="10011";b.boxDiv.style.left="20px";b.boxDiv.style.top="57px"}},isAvailable:function(){var a=CoordBox;return!(a.boxDiv==null)}}

var battleReports = {
  init : function (){
    var t = battleReports; 
    t.renderBattleReportFunc = new CalterUwFunc ('Messages.viewMarchReport', [['$("modal_msg_list").innerHTML=cm.MarchReportController.getMarchReport(c,w)','var msg=cm.MarchReportController.getMarchReport(c,w); $("modal_msg_list").innerHTML = renderBattleReport_hook(msg,c,w);']]); //March reports battle rounds function
    //unsafeWindow.renderBattleReport_hook = t.hook2;
    //t.renderBattleReportFunc.setEnable (true);
    //unsafeWindow.deleteAreport = t.e_deleteReport;
    
  },
  e_deleteReport : function (rptid){    var t = battleReports;     t.ajaxDeleteMyReport (rptid);  },
   ajaxDeleteMyReport : function (rptid, isUnread, side, isCityReport, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.s0rids = rptid;
    params.s1rids = '';
    params.cityrids = '';
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (rslt.ok && isUnread){
          unsafeWindow.seed.newReportCount = parseInt(unsafeWindow.seed.newReportCount) - 1;
          unsafeWindow.messages_notify_bug()
        }    
        unsafeWindow.Messages.listReports();
        if (notify)
          notify (rslt.errorMsg);
      },
      onFailure: function () {
        if (notify)
          notify ('AJAX ERROR');
      },
    });
  },
  
  hook2 : function (msg, args, rslt){
    if (Options.reportDeleteButton){
  	msg = msg.replace(/Reports<\/a>/im, 'Reports</a><a class=\'button20\' onclick=\'deleteAreport('+args[0]+',false)\'><span>'+unsafeWindow.g_js_strings.commonstr.deletetx+'</span></a>'); //Delete button
			return msg;
    }else {
     return msg;
    }
  },

}
var ChatStuff = {
  chatDivContentFunc : null,
  getChatFunc : null,
  leaders : {},
  init : function (){
  
 
    var t = ChatStuff; 
    	if(getMyAlliance()[0] > 0)
		t.getAllianceLeaders();
    t.chatDivContentFunc = new CalterUwFunc ('Chat.chatDivContent', [['return f.join("");', 'var msg = f.join("");\n msg=chatDivContent_hook(msg);\n return msg;']]);
    unsafeWindow.chatDivContent_hook = t.chatDivContentHook;
    unsafeWindow.ptChatIconClicked = t.e_iconClicked;
    unsafeWindow.BOAttackDetect = t.attaque;
    unsafeWindow.BOTransportDetect = t.transport;
    t.setEnable (Options.chatEnhance);
  },
  isAvailable : function (){
    var t = ChatStuff; 
    t.chatDivContentFunc.isAvailable ();
  },
  transport: function(x,y) {
     var t = ChatStuff; 
     if (!Options.pbWinIsOpen)
        nHtml.Click(ById("ptBoite"));
     

      
      setTimeout(function(){
      
        nHtml.Click(ById("pbtcTranspAuto").firstChild.firstChild);
        
          setTimeout(function() {
	
	      Tabs.TranspAuto.destinationCityx.value = x;
	      Tabs.TranspAuto.destinationCityy.value = y;
	      Tabs.TranspAuto.estimerRes();
	     
   }, 100);
        
       }, 100);
//  tabManager.e_clickedTab(e);
      //tabManager.e_clickedTab(ById("pbtcTranspAuto"));
      //Tabs.TranspAuto.show();
    
  
  },
  attaque: function(x,y) {
   var t = ChatStuff; 
   if (Options.ptWin2IsOpen){
     nHtml.Click(ById("sppAttaque"));
   } else {
   
     nHtml.Click(ById("ptBoite2"));
     nHtml.Click(ById("sppAttaque"));
   }
  
   setTimeout(function() {
    ById("RAAtypetrpx").value=x;
    ById("RAAtypetrpy").value=y;
    myBO.Attaque.estimerRes();
   
   }, 100);
  
  
  },
  setEnable : function (tf){
    var t = ChatStuff; 
    t.chatDivContentFunc.setEnable (tf);
    if(ById("mod_comm_list1"))
      ById("mod_comm_list1").style.backgroundColor = Colors.ChatGlo;
  },
  e_iconClicked : function (name){
    ById('mod_comm_input').value='';
    var e = ById('mod_comm_input');
    name = name.replace(/Â°Â°/g,"'");
    e.value = '@'+ name +' ';
    e.focus();   
  },
    
  chatDivContentHook : function (msg){
    var t = ChatStuff; 
    var classs = '';
    var classsinfo='';
    var m = /div class='info'>.*<\/div>/im.exec(msg);
     if (m == null)
      return msg;      
    var whisp = m[0];    
        
    if (m[0].indexOf('Type : ECLAIREUR') >= 0)
      classs = 'ptChatScout';
    else if (m[0].indexOf('Type : ATTAQUE') >= 0 || m[0].indexOf('ANGRIFF') >=0 || m[0].indexOf('Incoming Troops') >= 0)
      classs = 'ptChatAttack';
    else if (m[0].indexOf('to the alliance')>= 0 || m[0].indexOf("alliance:") >= 0)
      classs = 'ptChatAlliance'; 
    else if (m[0].indexOf('chuchote') >= 0 || m[0].indexOf('whispers to') >= 0) 
      classs = 'ptChatWhisper';
    else  
      classs = 'ptChatGlobal'; 
   var scripters = ["11653192","14904449"];
   var yoman = ["11657114","5474699","15788946","14778807","6809698"];
   var suid = /viewProfile\(this,([0-9]+),false/i.exec(m[0]);
    if(!suid)
    		suid = unsafeWindow.tvuid;
    	else
		suid = suid[1];
	if (t.leaders[suid] && Options.ChatLearder) classsinfo = 'ptChat'+t.leaders[suid];
	if (avatars[suid]) {
	      msg = msg.replace (/\bhttps\:\/\/[-a-z].*png'/i, avatars[suid] + "'");	
	}
	if (scripters.indexOf(suid) >= 0) {
	  classs += ' ptChatScripter';
	}
    msg = msg.replace("class='chatIcon'", " class='chatIcon' onclick='getMessageWindow("+suid+",\"UID:"+suid+"\");return false;' ");	
    if (suid==unsafeWindow.tvuid && Options.icon_chat)
	msg = msg.replace (/\bhttps\:\/\/[-a-z].*png'/i, Options.URLicon+"'");
    msg = msg.replace ("class='content'", "class='content "+ classs +"'");
    msg = msg.replace ("class='nm'", "class='nm "+ classsinfo +"'");   
    if (msg.indexOf('claimAllianceChat')<0)
      msg = msg.replace (/([0-9]{1,3})\s*(,|-)\s*([0-9]{1,3})/img, '$1,$3');
    if (classs.indexOf('ptChatWhisper')>=0 && Options.WhisperOn && (m[0].indexOf('te chuchote:') || m[0].indexOf('whispers to'))) {
      msg = msg.replace ('whispers to','<font size=1px color=red> te murmure </font><span style="visibility:hidden"><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" width="10" height="10" id="dewplayer" name="dewplayer"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3='+Options.URLson1+'&amp;autostart=1&amp;showtime=1&amp;volume=100" /></object></span>'); 
      msg = msg.replace ('te chuchote:','<font size=1px color=red> te murmure </font><span style="visibility:hidden"><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" width="10" height="10" id="dewplayer" name="dewplayer"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3='+Options.URLson1+'&amp;autostart=1&amp;showtime=1&amp;volume=100" /></object></span>');   
   }
  if (scripters.indexOf(suid) >= 0 || yoman.indexOf(suid) >= 0) {
      msg = msg.replace ('(Creeds)','<img style="width:200px !important;height:200px !important" src=http://www.gamesetwatch.com/GSW%20Ubi%204.jpg><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://28.media.v4.skyrock.net/music/281/f62/281f6218b4e2da83c89412191cac497a.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');
      msg = msg.replace ('(Limousin)','<img style="width:300px !important;height:262px !important" src=http://t1.gstatic.com/images?q=tbn:ANd9GcT2jk0Msi8GLoyK7ntVJ2WK_DfFc8mZDD6itXQQhWWoPvf_eo80><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/7768.MP3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');  
      msg = msg.replace ('(Banzai)','<img style="width:200px !important;height:200px !important" src=http://philhenri81.files.wordpress.com/2011/09/banzai-eps.jpg><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/11927.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');
      msg = msg.replace ('(Wazza)','<img style="width:200px !important;height:200px !important" src=http://3.bp.blogspot.com/_TRqzr1iUO8g/TO1dFCYrivI/AAAAAAAAAAQ/42Pa-DSUI5E/s1600/wazza1.jpg><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/11502.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');
      msg = msg.replace ('(Naboo)','<img style="width:230px !important;height:306px !important" src=http://i34.servimg.com/u/f34/11/17/34/83/affclo10.jpg><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://dc347.4shared.com/img/367232169/6085cd99/dlink__2Fdownload_2FcffFINzZ_3Ftsid_3D00000000-000000-00000000/preview.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=100" /></object></span>');
      msg = msg.replace ('(StarWars1)','<img style="width:147px !important;height:170px !important" src=http://3.bp.blogspot.com/-0-T3C9VLMA8/TZYqnKvyJWI/AAAAAAAAADY/MdI5iK4Qqjw/s170/Yoda_SWSB.jpg><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/8485.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=100" /></object></span>');
      msg = msg.replace ('(StarWars2)','<img style="width:147px !important;height:170px !important" src=http://3.bp.blogspot.com/-0-T3C9VLMA8/TZYqnKvyJWI/AAAAAAAAADY/MdI5iK4Qqjw/s170/Yoda_SWSB.jpg><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/8490.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=100" /></object></span>');
      msg = msg.replace ('(Rot)','<img style="width:200px !important;height:202px !important" src=http://profile.ak.fbcdn.net/hprofile-ak-snc4/71157_176209315905_7432329_n.jpg><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/11941.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=100" /></object></span>');
 }
  if (Options.EclaireurOn && classs.indexOf('ptChatScout')>=0 && m[0].indexOf(' ** ARRIVEE ** ')) {
     msg = msg.replace (' ** ARRIVEE ** ',' *** ARRIVEE *** <span style="visibility:hidden"><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" width="10" height="10" id="dewplayer1" name="dewplayer1"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3='+Options.URLson4+'&amp;autostart=1&amp;showtime=1&amp;volume=100" /></object></span>'); 
  }
  if (m[0].indexOf('Ma ville') >= 0 && m[0].indexOf('a besoin de pommes.') >= 0) {
   try {
          var testt = /;'> ([0-9]+),<span><\/span>([0-9]+) <\/a>#/i.exec(m[0]);
          if (testt) {
             msg +='<div onclick="BOTransportDetect('+parseIntNan(testt[1])+','+parseIntNan(testt[2])+')" style="position: absolute; background-image: url(\'\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 3px; top: 30px; "></div>';
          }
         } catch(e) {
       }
  
  }
  if (classs.indexOf('ptChatAttack')>=0 && m[0].indexOf('Type : ATTAQUE') >= 0 && m[0].indexOf('Cible :') >= 0) {
       try {
        var testt = /;'> ([0-9]+),<span><\/span>([0-9]+) <\/a>#/i.exec(m[0]);
        if (testt) {
           msg +='<div onclick="BOAttackDetect('+parseIntNan(testt[1])+','+parseIntNan(testt[2])+')" style="position: absolute; background-image: url(\'\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
        }
       } catch(e) {
       }
     }
 if (classs.indexOf('ptChatScout')>=0 && m[0].indexOf('Type : ECLAIREUR') >= 0 && m[0].indexOf('Cible :') >= 0) {
  try {
         var testt = /;'> ([0-9]+),<span><\/span>([0-9]+) <\/a>#/i.exec(m[0]);
         if (testt) {
            msg +='<div onclick="BOAttackDetect('+parseIntNan(testt[1])+','+parseIntNan(testt[2])+')" style="position: absolute; background-image: url(\'%3D\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
         }
        } catch(e) {
       }
 
 }
  if (Options.AttaqueOn && classs.indexOf('ptChatAttack')>=0 && (m[0].indexOf(' ** ARRIVEE ** ') || m[0].indexOf('ANGRIFF'))) {
    
     msg = msg.replace (' ** ARRIVEE ** ',' *** ARRIVEE *** <span style="visibility:hidden"><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" width="10" height="10" id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3='+Options.URLson2+'&amp;autostart=1&amp;showtime=1&amp;volume=100" /></object></span>'); 
     msg = msg.replace ('ANGRIFF','<font size=1px color=red> ATTAQUE MULTI </font><span style="visibility:hidden"><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" width="10" height="10" id="dewplayer" name="dewplayer"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3='+Options.URLson2+'&amp;autostart=1&amp;showtime=1&amp;volume=100" /></object></span>');   

   }
    var m = /(Lord|Lady) (.*?)</im.exec(msg);
    if (m != null)
      msg = msg.replace (/<img (.*?>)/img, '<A onclick=ptChatIconClicked(\"'+ m[2] +'\")><img class=\"ptChatIcon\" $1</a>');
    if (Options.Smiley) {
   
      for (k in Smileys) {
       
        if (k=="(massage)")
          msg=msg.replace(k, '<img style="width:32px !important;height:24px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="*kissing*")
          msg=msg.replace(k, '<img style="width:47px !important;height:30px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else  if (k=="(fouet)")
          msg=msg.replace(k, '<img style="width:60px !important;height:30px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(sonic)")
          msg=msg.replace(k, '<img style="width:64px !important;height:64px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if ( k=="(renne)" || k=="(tigre)" || k=="(girafe)" || k=="(elephant)" || k=="(rat)")
          msg=msg.replace(k, '<img style="width:60px !important;height:60px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(spider)")
          msg=msg.replace(k, '<img style="width:95px !important;height:57px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(hamta)" || k=="(cat)")
          msg=msg.replace(k, '<img style="width:31px !important;height:40px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(shark2)")
          msg=msg.replace(k, '<img style="width:117px !important;height:50px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(concombre)")
          msg=msg.replace(k, '<img style="width:100px !important;height:50px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(baby)")
          msg=msg.replace(k, '<img style="width:56px !important;height:40px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="]:->" || k=="(pingouin)" || k=="(shark)")
          msg=msg.replace(k, '<img style="width:35px !important;height:35px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(bath)" || k=="(emotlove2)" || k=="(smyno)")
          msg=msg.replace(k, '<img style="width:40px !important;height:40px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(miroir)")
          msg=msg.replace(k, '<img style="width:45px !important;height:45px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(caribou)")
          msg=msg.replace(k, '<img style="width:65px !important;height:33px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(magebarbe)")
          msg=msg.replace(k, '<img style="width:45px !important;height:45px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else if (k=="(couette)" || k=="(ver)")
          msg=msg.replace(k, '<img style="width:60px !important;height:45px !important" class=emoicon src=\"'+Smileys[k]+'\">');
        else if (k=="(fox)" || k=="(heidy)")
          msg=msg.replace(k, '<img style="width:30px !important;height:30px !important" class=emoicon src=\"'+Smileys[k]+'\">');
        else if (k=="(autruche)")
          msg=msg.replace(k, '<img style="width:93px !important;height:84px !important" class=emoicon src=\"'+Smileys[k]+'\">');
        else if (k=="(panda)" || k=="(crabe)" || k=="(tortue)"|| k=="(vache)" || k=="(singe)" || k=="(bravo2)" || k=="(bubulle)" || k=="(chien)" || k=="(cuicui)" || k=="(bubulle)" || k=="(cochon)" || k=="(lapin)" || k=="(grenouille)")
	  msg=msg.replace(k, '<img style="width:66px !important;height:66px !important" class=emoicon src=\"'+Smileys[k]+'\">');
        else if (k=="(herisson)" || k=="(lion)" || k=="(chat)"  || k=="(serpent)" || k=="(dragon)" || k=="(camelot)")
          msg=msg.replace(k, '<img style="width:77px !important;height:77px !important" class=emoicon src=\"'+Smileys[k]+'\">');
        else if (k=="(ours)" || k=="(taupe)" )
          msg=msg.replace(k, '<img style="width:88px !important;height:88px !important" class=emoicon src=\"'+Smileys[k]+'\">')
        else if (k=="(bienmal)")
          msg=msg.replace(k, '<img style="width:109px !important;height:60px !important" class=emoicon src=\"'+Smileys[k]+'\">')
        else if (k=="(aigle)")
          msg=msg.replace(k, '<img style="width:65px !important;height:100px !important" class=emoicon src=\"'+Smileys[k]+'\">');
        else if (k=="(hippo)")
          msg=msg.replace(k, '<img style="width:73px !important;height:115px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	 else if (k=="(lapin1)" || k=="(lapin2)" || k=="(lapin3)")
          msg=msg.replace(k, '<img style="width:96px !important;height:96px !important" class=emoicon src=\"'+Smileys[k]+'\">');
	else
	  msg=msg.replace(k, '<img class=emoicon src=\"'+Smileys[k]+'\">');
    }
        
   }      
   return msg;
  },
  getAllianceLeaders : function (){
   var t = ChatStuff;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetLeaders.php" + unsafeWindow.g_ajaxsuffix, {
		 method: "post",
		 parameters: params,
		 loading: true,
		 onSuccess: function (rslt) {
			 if (rslt.officers) {
				for (uid in rslt.officers) {
					var user = rslt.officers[uid];
					t.leaders[user.userId] = user.type.substr(0,4);
				}
			 } 
		},
		onFailure: function () {}
  		});
	},
}

var knightRoles = [['Contremaitre', 'politics', 'Pol'],['Mar&eacute;chal', 'combat', 'Com'],['Alchimiste', 'intelligence', 'Int'],['R&eacute;gisseur', 'resourcefulness', 'Res']];
var CheckTournoi={init:function(){var a=CheckTournoi;a.e_eachMinute()},minuteTimer:null,e_eachMinute:function(){var f=CheckTournoi;var now=unixTime();row=[];if(Options.enableCheckTournoi){var params=unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);params.format=2;params.tournyPos=0;new AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/getLeaderboard.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,onSuccess:function(transport){var rslt=eval("("+transport.responseText+")");if(rslt.ok){if(rslt.data){ById("ptBoite2").innerHTML='<span style="color: #f66"><blink>TOURNOI</blink></span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" width="10" height="10" id="dewplayer1" name="dewplayer1"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/7289.MP3&autostart=1&showtime=1&volume=100" />';setTimeout(function(){var a="REVEILLES-TOI, UN TOURNOI VIENT DE COMMENCER !!!! WAZZZZZZZZAAAAAAAAAAAAAAAAA";sendChat("/"+Seed.player.name+" "+a);var b="DEBUT TOURNOI SUR "+unsafeWindow.domainName;if(Options.alertConfig.emailAddress!="")sendEmail(Seed.player.name,"",Options.alertConfig.emailAddress,b,a)},1e3);Options.enableCheckTournoi=false;saveOptions()}}}});f.minuteTimer=setTimeout(f.e_eachMinute,6e5)}}}
function formatUnixTime(a,b){var c=unsafeWindow.formatDateByUnixTime(a);return c}
function readTrainingOptions(){var a=getServerId();s=GM_getValue("TrainingOptions_"+a);if(s!=null){opts=JSON2.parse(s);for(k in opts){TrainOptions[k]=opts[k]}}}
function saveTrainingOptions(){var a=getServerId();setTimeout(function(){GM_setValue("TrainingOptions_"+a,JSON2.stringify(TrainOptions))},0)}

myBO.Overview = {
  cont : null,
  displayTimer : null,
  checkBox:null,
  checkBox1:null,
  Overview : function (){
  },
  init : function (){
    this.cont = document.createElement('div');
    return this.cont;
  },
  getContent : function (){
    return myBO.Overview.cont;
  },
  hide : function (){
    clearTimeout (myBO.Overview.displayTimer);
  },
  show : function (){
    var rownum = 0;
    var totalentre = 0;  
    var t = myBO.Overview;
    clearTimeout (t.displayTimer);
    function _row (name, row, noTotal, typee){
      if (rownum++ % 2)
        style = '';
      else
        style = ' style = "background: #e8e8e8"';
      var tot = 0;
      var m = [];
      m.push ('<TR style="background: #fff" align=right');
      m.push (style);
      m.push ('><TD');
      m.push (style);
      m.push ('><B>');
      m.push (name);
      m.push ('</td>');
      if (noTotal){
        m.push ('<TD');
        m.push (style);
        m.push ('>&nbsp;</td>');
      } else {
        for (i=0; i<row.length; i++)
          tot += row[i];
        m.push ('<TD style="background: #ffc">');
         if (tot<0) {
          m.push ("<SPAN class=class=boldRed>"+addCommas(tot)+"</span>");
         } else {
          m.push (addCommas(tot));
         }
        m.push ('</td>');
      }
      for (i=0; i<row.length; i++){
        m.push ('<TD');
        m.push (style);
        m.push ('>');
        m.push (addCommas(row[i]));
        m.push ('</td>');
      }
      m.push ('</tr>');
      return m.join('');
    }
    try {
      if (Options.includeMarching)
        march = getMarchInfo ();
      dt = new Date ();
      dt.setTime (Seed.player.datejoinUnixTime * 1000);
      var now = unixTime();
      str = "<DIV class=boStat><b>STOCK ET PRODUCTION</b></div><TABLE class=ptTabLined cellspacing=0><TR valign=top align=right><TD width=65></td><TD width=88 style='background: #ffc'><B>TOTAL</b></td>";
      for(i=0; i<Cities.numCities; i++) {
         str += "<TD width=81><B>"+ Cities.cities[i].name.substring(0,10) +'</b></td>';
      }
      if (Options.includeMarching)
        str += '<TD width=81><B>'+uW.g_js_strings.commonstr.marching+'</b></td>';
      str += "<td></td></tr>";
      rows = [];
      rows[0] = [];
      for(i=0; i<Cities.numCities; i++) {
        cityID = 'city'+ Cities.cities[i].id;
        rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
      }
      for (r=1; r<6; r++){
        rows[r] = [];
        for(i=0; i<Cities.numCities; i++) {
          cityID = 'city'+ Cities.cities[i].id;
           if (r==5)
	  	    rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
	  	            else
           rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
        }
      }
      if (Options.includeMarching){
        for (var i=0; i<6; i++)
          rows[i][Cities.numCities] = march.resources[i];
      }
      str += _row ('<img title="Stock d\'or" height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_30.png>', rows[0], false, 0);
      str += _row ('<img title="Stock de nourriture" height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png>', rows[1], false, 0);
      str += _row ('<img title="Stock de bois" height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png>', rows[2], false, 0);
      str += _row ('<img title="Stock de pierre" height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png>', rows[3], false, 0);
      str += _row ('<img title="Stock de minerais" height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png>', rows[4], false, 0);
      str += _row ('<img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png>', rows[5], false, 0);
    str += '<TR><TD><BR></td></tr>';
    row = [];
      for(i=0; i<Cities.numCities; i++) {
                  var rp = getResourceProduction (Cities.cities[i].id);
                  row[i] = rp[1];
      }
      str += _row ('<img height=18 title="Production de nourriture a l\'heure" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png>', row, false, 0);
    row = [];
            for(i=0; i<Cities.numCities; i++) {
                        var rp = getResourceProduction (Cities.cities[i].id);
                        row[i] = rp[2];
            }
            str += _row ('<img height=18 title="Production de bois a l\'heure" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png>', row, false, 0);
 row = [];
      for(i=0; i<Cities.numCities; i++) {
                  var rp = getResourceProduction (Cities.cities[i].id);
                  row[i] = rp[3];
      }
      str += _row ('<img height=18 title="Production de pierre a l\'heure" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png>', row, false, 0);
 row = [];
      for(i=0; i<Cities.numCities; i++) {
                  var rp = getResourceProduction (Cities.cities[i].id);
                  row[i] = rp[4];
      }
  str += _row ('<img height=18 title="Production de minerais a l\'heure" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png>', row, false, 0);
  str += '<TR><TD><font size=1><BR></td></tr>';
  row = [];
            var totalbouffe = 0;
            for(i=0; i<Cities.numCities; i++) {
              var rp = getResourceProduction (Cities.cities[i].id);
              var usage = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
              row[i] = rp[1] - usage;
            }
            str += _row ('Prod', row, false,  0);
            for(i=0; i<Cities.numCities; i++) {
              if (row[i] >= 0)
                row[i] = '----';
              else {
                var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-row[i]) * 3600;
                if (timeLeft > 86313600)
                  row[i] = '----';
                else {
                  if (Options.enableFoodWarn && timeLeft<(Options.foodWarnHours*3600))
                    row[i] = '<SPAN class=whiteOnRed>'+ timestrShort(timeLeft) +'</span>';
                  else
                    row[i] = timestrShort(timeLeft);
                }
              }
            }    
      str += _row ('Aut.', row, true, 0);
      str += '<TR><TD><font size=1><BR></td></tr>';
      for (r=1; r<13; r++){
        rows[r] = [];
        for(i=0; i<Cities.numCities; i++) {
          cityID = 'city'+ Cities.cities[i].id;
          rows[r][i] = parseInt(Seed.units[cityID]['unt'+r]);
        }
      }
      if (Options.includeMarching){
        for (var i=0; i<13; i++)
          rows[i][Cities.numCities] = march.marchUnits[i];
      } 
      str += "</table>";
      myBO.Overview.cont.innerHTML = str;
    } catch (e){
      myBO.Overview.cont.innerHTML = '<PRE>'+ e.name +' : '+ e.message +'</pre>';
    }   
    t.displayTimer = setTimeout (t.show, 5000);
  },
};
myBO.Attaque = {
 cont : null,
 displayTimer : null,
 state : null,
 curTabBut : null,
 curTabName : null,
 BOAttackTimer: null,
 sourceCity : {},
 destinationCity : {},
 rows : [],
 iused : new Array(),
 init : function (){
   var t = myBO.Attaque;
   t.cont = document.createElement('div');
   t.state = null;
   clearTimeout (t.displayTimer);
   return t.cont;
 },
  getContent : function (){
    var t = myBO.Attaque;
    return t.cont;
  },
  hide : function (){
    var t = myBO.Attaque;
    t.state = null;
    clearTimeout (t.displayTimer);
  },
  show : function (){  
    var t = myBO.Attaque;
    var rownum = 0;
    var ModelCity = {};
    if (t.state == null) {  
         m = "<DIV class=boStat><b>ATTAQUER ou RENFORCER RAPIDEMENT</b> - <input type=button value='?' id=boaideattaquer class=boAide></div>";
         m +="<div id='statpourRAA'></div>";       
         m += "<TABLE width=600 class=ptTab border=0 align=center>\
           <tr><td colspan=4 align=center><input type=button id=REEaction value='Eclairer'>&nbsp;<input type=button id=RAAaction value='Attaquer'>&nbsp;<input type=button id=RENaction value='Renforcer'>&nbsp;<input type=button id=RENBaction value='Renforcer + Nourriture'></td></tr><tr align=center valign=top><td colspan=1 width=130><b><u>Source</b></u><br><span id=RAAsrcRptspeedcity></span></td>\
           <td colspan=1><b><u>Destination</b></u><br>X:<input type=text id=RAAtypetrpx size=3>&nbsp;Y:<input type=text id=RAAtypetrpy size=3><br><a href='javascript:void(0);' id='BOchargelistelieux'>Membres</a> : <select id='listeFavori'></select></td>\
           <td><b><u>Distance</u></b><br><span id='BOEstimationD'>&nbsp;</span><td><b><u>Ville la plus proche</u></b><br><span id=BOVilleProche></span>\
           </tr><tr align=center valign=top>\
           <td colspan=4 align=left><table border=0 bordercolor=black cellspacing=0 cellpadding=0 width=100% style='text-align:center'><tr><td rowspan=13><div id=RAAstatsource></div></td><td colspan=2><a href='javascript:void(0)' id=BO_RAZ_Units>Unit&eacute;e</a></td><td>Tps Attaque</td><td>Tps Renfort</td></tr>";
            for (r=1; r<13; r++){
   	     m += '<tr><td align=right><img height=20 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="RAAnbunit'+r+'" type=text size=7 value="0" ></td><td><span id="BOEstimationTT'+r+'">&nbsp;</span></td><td><span id="BOEstimationTZ'+r+'">&nbsp;</span></td></tr>';
      	}
      	var itemlist=[55,57,931,932];
	var BOitems="";
	for(var i=0;i<itemlist.length;i++){
		 BOitems += "<img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/30/"+itemlist[i]+".jpg' /><input type=checkbox id='BOitem_"+itemlist[i]+"'><span id='BOitemSpan_"+itemlist[i]+"'>" + unsafeWindow.ksoItems[itemlist[i]].count + "</span>&nbsp;";
        }
        m += "</table></td></tr>\
              <tr><td colspan=2>Chevalier : <SELECT id='RAApiKnight' type=list></select> (en option)<br>"+BOitems+"</td><td colspan=2><div id=BOinfodest></div><center><input type=button value='Actualiser' id=BOrechdest></td></tr>\
              <tr><td colspan=4><b><div class=boStat>Unit&eacute;es Favorites :</div></tr><tr><td colspan=2><select id=BO_AT_Fav></select><input type=button value='Sup' id=BO_AT_Fav_Sup><input type=button value='Tout Sup' id=BO_AT_Fav_RESET></td><td colspan=2>Nouveau : <input type=type id=BO_AT_Fav_Nom size=10 maxlength=12>&nbsp;<input type=checkbox id=BO_AT_Fav_Coo> coords&nbsp;<input type=button value='Enregistrer' id=BO_AT_Fav_ajou>\
              <tr><td colspan=4><div id=ptRAAStatus style='overflow-y:auto; max-height:50px; height: 50px;'></div></td></tr>\
              <tr><td colspan=4><b><div class=boStat>Programmer une attaque</div></tr><tr><td><input type=button id='BOActiveAttack' value='ACTIVER : OFF' ></td><td colspan=3><span id='BOCompAttack'></span></tr>\
              <tr><td><b>Heure arriv&eacute;e :</b> <input type=text size=7 id='BOHorloge' value='" + Options.AttackHorloge + "'></td><td><input type=button value='Enregistrer' id='BOSaveAttack'></td><td><input type=button value='Editer l\'attaque' id='BOEditAttack' disabled></td></tr>\
              <tr><td colspan=4><span id='BOAttackProg'></span></td></tr></table>";
        t.cont.innerHTML = m; 
        t.statpourRAA = ById ('statpourRAA');
        t.Favoris = ById('BO_AT_Fav');
        t.BOinfodest = ById('BOinfodest');
        t.BOrechdest = ById("BOrechdest");
         ById('boaideattaquer').addEventListener('click', function(){
	       	 window.open(sitesupport+"?page=aide_attaquer");
    	} , false);
        t.BOrechdest.addEventListener ('click', function() {
         t.rechercheDEST();
        }, false); 
	function metajourfavori() {
	       t.Favoris.innerHTML="<option value=''>...</option>";
	       var lisf = Options.AttackFav;
	       for (var m in lisf) {
	         var lis = lisf[m];
	         if (lis!=null)
	          t.Favoris.innerHTML+="<option value='"+m+"'>"+lis[0]+"</option>";
      	       }  
	}
       ById("BO_AT_Fav_RESET").addEventListener ('click', function() {
	 Options.AttackFav={};
	 saveOptions(); 
         metajourfavori();
       }, false); 
       ById("BO_AT_Fav_Sup").addEventListener ('click', function() {
       numfav=ById("BO_AT_Fav").value;
       if (numfav!="") {
        Options.AttackFav[numfav]={};
        delete Options.AttackFav[numfav];
        saveOptions(); 
        metajourfavori();
       }
       }, false); 
 	  ById("BO_RAZ_Units").addEventListener ('click', function() {
  	for (r=1; r<13; r++) ById("RAAnbunit"+r).value=0; 
 	}, false); 
       ById("BO_AT_Fav_ajou").addEventListener ('click', function() {
        if (ById("BO_AT_Fav_Nom").value=="") {
         alert("Merci de mettre un nom pour decrire votre favori !");
         return;
        }
        var a =ById("BO_AT_Fav_Nom").value;
        Options.AttackFav[a]={};
        var lisf = Options.AttackFav[a];
        lisf[0]=ById("BO_AT_Fav_Nom").value;
        for (r=1; r<13; r++) lisf[r]=ById("RAAnbunit"+r).value;
        if (ById("BO_AT_Fav_Coo").checked) {
         lisf[13]=t.destinationCityx.value;
         lisf[14]=t.destinationCityy.value;

        }
        ById("BO_AT_Fav_Coo").checked=false;
        ById("BO_AT_Fav_Nom").value="";
        saveOptions(); 
	metajourfavori();
       }, false); 
       ById("BO_AT_Fav").addEventListener ('change', function() {
         numfav=ById("BO_AT_Fav").value;
         if (numfav=="") {
          for (r=1; r<13; r++) ById("RAAnbunit"+r).value=0; 
         }else {
          var lisf = Options.AttackFav[numfav];
          for (var m in lisf) {
           if(m>0 && m<13)
	    if (ById("RAAnbunit"+m)) ById("RAAnbunit"+m).value=lisf[m];
	   if (m==13)
	    if (lisf[m]>0)
	     t.destinationCityx.value=lisf[m];
	   if (m==14)
	    if (lisf[m]>0) 
	     t.destinationCityy.value=lisf[m];
	  }
         }
       }, false); 
       ById("BOitem_55").addEventListener ('click', function() {
        ById("BOitem_57").checked=false;
        t.estimerRes();
       }, false);  
       ById("BOitem_57").addEventListener ('click', function() {
              ById("BOitem_55").checked=false;
              t.estimerRes();
       }, false);
        t.statutRAA = ById ('ptRAAStatus');
        t.destinationCityx = ById ('RAAtypetrpx');
        t.destinationCityy = ById ('RAAtypetrpy');
        t.destinationCityx.value = Options.Xrenfort;
        t.destinationCityy.value = Options.Yrenfort;
        if (ById ('maparea_map').style.display!="none") {
         t.destinationCityx.value = ById ('mapXCoor').value;
         t.destinationCityy.value = ById ('mapYCoor').value;
         t.rechercheDEST();
        }
        t.listeFavoris = ById ('listeFavori');
        t.listeFavoris.addEventListener ('change', t.SelectFavoris, false);
        t.chargelistelieux = ById ('BOchargelistelieux');
        t.chargelistelieux.addEventListener ('click', t.chercherFavoris, false);
        t.actionREN = ById ('RENaction');
        t.actionRENB = ById ('RENBaction');
        t.actionREE = ById ('REEaction');
        t.actionRAA = ById ('RAAaction');
  	t.actionREN.addEventListener ('click', function () { t.clickATTAQUEDo(2,0); }, false);
        t.actionRAA.addEventListener ('click',  function () { t.clickATTAQUEDo(4,0); }, false);
        t.actionRENB.addEventListener ('click',  function () { t.clickATTAQUEDo(2,1); }, false);
        t.actionREE.addEventListener ('click',  function () { t.clickATTAQUEDo(3,0); }, false);
        t.destinationCityx.addEventListener ('keyup', function () { t.estimerRes(); }, false);
        t.destinationCityy.addEventListener ('keyup', function () { t.estimerRes(); }, false);       
        var dcp0 = new CdispCityPicker ('ptRAA0', ById('RAAsrcRptspeedcity'), false, t.clickRAACitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
        t.state = 1;
        t.estimerRes();
        t.BOAttackProg = ById ('BOAttackProg');
        t.BOHorloge = ById ('BOHorloge');
        t.BOSaveAttack = ById ('BOSaveAttack');
        t.BOEditAttack = ById ('BOEditAttack');
        t.BOCompAttack = ById ('BOCompAttack');
        t.BOActiveAttack  = ById ('BOActiveAttack');
        t.BOActiveAttack.addEventListener ('click', t.AutoattackOnOff, false);
        t.BOSaveAttack.addEventListener ('click', function () {
        var itemlist=[55,57,931,932];
	  for(var i=0;i<itemlist.length;i++){
	        ById('BOitemSpan_'+itemlist[i]).checked=false;
          }
         t.enregistreAttack();
        }, false);
        if (Options.AttackCibleX!=0 && Options.AttackCibleY!=0) {
         t.BOEditAttack.disabled=false;
        }
        t.BOEditAttack.addEventListener ('click', function () { 
          t.destinationCityx.value = Options.AttackCibleX;
          t.destinationCityy.value = Options.AttackCibleY;
          ById("RAApiKnight").value=Options.AttackKnight;
          nHtml.Click(ById("ptRAA0_"+Cities.byID[Options.AttackFromCity].idx)); 
          for (r=1; r<13; r++) {
	      ById("RAAnbunit"+r).value=Options.AttackUnits[r-1];
          }
        }, false);
        metajourfavori();
        if (Options.AttackOnOff) {
          t.BOActiveAttack.value='ACTIVER : ON';
    	  t.activeAttack();
        }
       }
    },
    MapAjax : new CMapAjax(),
    rechercheDEST:function() {
     var t = myBO.Attaque;
     t.BOinfodest.innerHTML="<center>Recherche...</center>";
     var xcoord=t.destinationCityx.value;
     var ycoord=t.destinationCityy.value;
     t.MapAjax.request (xcoord, ycoord, 1, function(left, top, width, rslt) {
       	   map = rslt.data;	
     	   for (k in map){
		   if (xcoord==map[k].xCoord && ycoord==map[k].yCoord) {
		    var m="";
		    var uid=map[k].tileUserId;
		    if (uid==null || uid==0) {
		     t.BOinfodest.innerHTML="non dispo";
		     return;
		    }
		    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		               params.checkArr = uid;
		               new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
		                 method: "post",
		                 parameters: params,
		               onSuccess: function (rslt) {
		                  var p = rslt.data;
		         	  if (p[uid] == true) {
		         	         m = '<span style="color:green"><b>Joueur en Ligne !</b></span>';
		         	       } else {
		         	          m = '<center><span style="color:red"><b>Joueur pas en ligne</b></span>';
		                   }  
		                   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
			           params.pid = uid;
				   new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
				         method: "post",
				         parameters: params,
				         onSuccess: function (rslt) {
				            t.BOinfodest.innerHTML="<center><b>" + rslt.playerInfo.displayName+"</b><bR>"+m;
				         },
				         onFailure: function (rslt) {},
    				   }); 
		             },onFailure: function (rslt) {},
			 });
		  }
           }
     });
    },
    AutoattackOnOff:function() {
     var t = myBO.Attaque;
     t.BOCompAttack.innerHTML='';
     clearTimeout (t.BOAttackTimer);
     if (t.BOActiveAttack.value=='ACTIVER : OFF') {
    	t.BOActiveAttack.value='ACTIVER : ON';
    	     Options.AttackOnOff = true;
    	     saveOptions();  
    	     t.activeAttack();
    	     
    	    } else {
    	     Options.AttackOnOff = false;
    	     saveOptions();  
    	     t.BOActiveAttack.value='ACTIVER : OFF';   
    }   
    },
    activeAttack:function() {
     var t = myBO.Attaque;
     clearTimeout (t.BOAttackTimer);
     if (Options.AttackGoHorloge) {
       var depart=new Date()
       depart.setTime(Options.AttackGoHorloge);
       var now = unixTime()*1000;
       if (now >= Options.AttackGoHorloge) {
	t.BOCompAttack.innerHTML='<center><font color=red>LANCEMENT ATTAQUE EFFECTUE</font></center>';
	t.destinationCityx.value = Options.AttackCibleX;
	t.destinationCityy.value = Options.AttackCibleY;
	ById("RAApiKnight").value=Options.AttackKnight;
	nHtml.Click(ById("ptRAA0_"+Cities.byID[Options.AttackFromCity].idx));
	for (r=1; r<13; r++) {
	   ById("RAAnbunit"+r).value=Options.AttackUnits[r-1];
          }
      t.clickATTAQUEDo(4,0);
      clearTimeout (t.BOAttackTimer);
      Options.AttackGoHorloge=null;
      Options.AttackOnOff = false;
      saveOptions(); 
      return;
     }
     if (now > depart.getTime()) {
         t.BOCompAttack.innerHTML='<center><font color=red>IMPOSSIBLE</font></center>';
         clearTimeout (t.BOAttackTimer);
       	 Options.AttackGoHorloge=null;
         saveOptions();  
         return false;
     }
     t.BOAttackTimer=setTimeout(function(){
        var depart=new Date();
	depart.setTime(Options.AttackGoHorloge);
        var now = unixTime()*1000;
        var tempsrestant = depart.getTime() - now;
        t.BOCompAttack.innerHTML='<center><font color=red><b>ATTAQUE DANS '+timestr(tempsrestant/1000)+'</b></font></center>';
        t.activeAttack();
      },1000);
     }
    },
    enregistreAttack : function() {
     var t = myBO.Attaque; 
     if (t.BOHorloge.value.match("^[0-9]{2}:[0-9]{2}:[0-9]{2}$")) {
       var horloge = t.BOHorloge.value;
       Options.AttackHorloge = horloge;
       var ndate=new Date();
       ndate.setHours(horloge.substr(0,2));
       ndate.setMinutes(horloge.substr(3,2));
       ndate.setSeconds(0);
       var atunits=new Array();
       for (r=1; r<13; r++) {
          atunits.push(parseInt(ById("RAAnbunit"+r).value));
       }
       Options.AttackUnits = atunits;
       Options.AttackFromCity = t.sourceCity.id;
       Options.AttackKnight = ById("RAApiKnight").value;
       Options.AttackCibleX = t.destinationCityx.value;
       Options.AttackCibleY = t.destinationCityy.value;
       
       var x1 = parseInt(t.sourceCity.x);
       var x2 = parseInt(t.destinationCityx.value);
       var y1 = parseInt(t.sourceCity.y);
       var y2 = parseInt(t.destinationCityy.value);
       var dist = distance (x1, y1, x2, y2);  
       var tempplusgrand=0;
       for (r=1; r<13; r++){
         if (parseInt(ById("RAAnbunit"+r).value)>0) {
               var m = estETA(dist, r, t.sourceCity.id,4);
               if (tempplusgrand<m.ETA) tempplusgrand=m.ETA;   
         }
       }
       var departtime=ndate.getTime() - (tempplusgrand*1000);
       var depart=new Date()
       depart.setTime(departtime);
       var now = unixTime()*1000;
       if (now > depart.getTime()) {
        t.BOAttackProg.innerHTML = "Depart impossible !";
        return false;
       }
       Options.AttackGoHorloge =  depart.getTime();
       saveOptions ();
       t.BOAttackProg.innerHTML = "Attaque sur " + Options.AttackCibleX + ","+ Options.AttackCibleY +" enregistr&eacute;e";
       t.BOEditAttack.disabled=false;
     } else {
      t.BOAttackProg.innerHTML = "Mauvais format de l'horloge.";
     }     
    },
    clickATTAQUEDo: function(typemarche, bouffe) {
      var t = myBO.Attaque;  
      var totalunit=0;
      if (typemarche==3 && ById("RAAnbunit3").value==0) ById("RAAnbunit3").value=1;
      for (r=1; r<13; r++){
         if (typemarche==3 && r!=3) {
          ById("RAAnbunit"+r).value=0;
         }
          if (parseInt(ById("RAAnbunit"+r).value) > parseInt(ById("RAAdestunit"+r).value)) {
            ById("RAAnbunit"+r).style.backgroundColor="red";
            return false;
          }
          totalunit=totalunit+parseInt(ById("RAAnbunit"+r).value);
          ById("RAAnbunit"+r).style.backgroundColor="";
      }
      var errMsg = "";
      if (isNaN (t.destinationCityx.value) ||t.destinationCityx.value<0 || t.destinationCityx.value>749)
            errMsg = "X doit &ecirc;tre entre 0 et 749<BR>"; 
      if (isNaN (t.destinationCityy.value) || t.destinationCityy.value<0 || t.destinationCityy.value>749)
       errMsg += "Y doit &ecirc;tre entre 0 et 749<br>";
      
      if (ById("RAApiKnight").value==0 && typemarche==4) {
       errMsg += "Impossible, vous n'avez pas choissi de chevalier !<BR>"; 
      }
      if (errMsg != "") {
           t.statutRAA.innerHTML = "<FONT COLOR=#550000>"+ errMsg +"</font>";
           return;
      }
      var x=t.destinationCityx.value;
      var y=t.destinationCityy.value;
      t.SaveCoordsOptions(x,y);
      var e=1;
      var f=uW.unixtime();
      if(Seed.playerEffects.aurasExpire){
      if(Seed.playerEffects.aurasExpire>f){e=1.15}}
      if(Seed.playerEffects.auras2Expire){if(Seed.playerEffects.auras2Expire>f){e=1.3}}
     var l_elem=ById("BOitem_931");
     if(l_elem&&l_elem.checked&&parseInt(Seed.items["i931"])>0){
       e+=0.25;
     }
     var l_elem=ById("BOitem_932");
     if(l_elem&&l_elem.checked&&parseInt(Seed.items["i932"])>0){
       e+=0.5;
     }
     var q=uW.cm.ThroneController.effectBonus(66);
     var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
     if (totalunit==0) {
         t.statutRAA.innerHTML = '<FONT COLOR=#550000>Impossible  avec 0 unit&eacute;e...!.</font>';
           return;
     }
     var niveauPointRall=parseInt(getCityBuilding (t.sourceCity.id, 12).maxLevel);
         var maxtroupe=parseInt(niveauPointRall*10000*e);
         if (niveauPointRall==11) maxtroupe=parseInt(150000*e);
         if (niveauPointRall==12) maxtroupe=parseInt(200000*e);
      
      maxtroupe=Math.round(maxtroupe*(1+q/100));
      if (totalunit>maxtroupe) {
       t.statutRAA.innerHTML = '<FONT COLOR=#550000>Impossible avec plus de '+maxtroupe+' unit&eacute;es a la fois.</font>';
       return;
      }
      var iused=new Array();
      var itemlist=[55,57,931,932];
      for(var i=0;i<itemlist.length;i++){
      
       var l_elem=ById("BOitem_"+itemlist[i]);
       if(l_elem&&l_elem.checked&&parseInt(Seed.items["i"+itemlist[i]])>0){
        iused.push(itemlist[i]);       
       }      
      }
      var res=0;
      if (bouffe==1) {
       for (var i=1;i<13;i++) {
        res += parseInt(unsafeWindow.unitstats['unt'+i][5] * ById("RAAnbunit"+i).value * (1 + (0.10 * Seed.tech.tch10)));
       }
       }
      params.items=iused.join(","); 
         params.cid= t.sourceCity.id;
         params.type = typemarche;
         params.xcoord = x;
         params.ycoord = y;
         if (typemarche==3)
           params.kid=0;
         else
   	   params.kid= ById("RAApiKnight").value;
	 params.r1 = res; 
	 params.u1 = 0;
  	 params.u2 = 0;
  	 params.u3 = 0;
  	 params.u4 = 0;
  	 params.u5 = 0;
  	 params.u6 = 0;
  	 params.u7 = 0;
  	 params.u8 = 0;
  	 params.u9 = 0;
  	 params.u10 = 0;
  	 params.u11 = 0;
 	 params.u12 = 0;
      if (typemarche!=3) {
        if (ById("RAAnbunit1").value>0) params.u1 = ById("RAAnbunit1").value;
	if (ById("RAAnbunit2").value>0) params.u2 = ById("RAAnbunit2").value;
	if (ById("RAAnbunit3").value>0) params.u3 = ById("RAAnbunit3").value;
	if (ById("RAAnbunit4").value>0) params.u4 = ById("RAAnbunit4").value;
	if (ById("RAAnbunit5").value>0) params.u5 = ById("RAAnbunit5").value;
	if (ById("RAAnbunit6").value>0) params.u6 = ById("RAAnbunit6").value;
	if (ById("RAAnbunit7").value>0) params.u7 = ById("RAAnbunit7").value;
	if (ById("RAAnbunit8").value>0) params.u8 = ById("RAAnbunit8").value;
	if (ById("RAAnbunit9").value>0) params.u9 = ById("RAAnbunit9").value;
	if (ById("RAAnbunit10").value>0) params.u10 = ById("RAAnbunit10").value;
	if (ById("RAAnbunit11").value>0) params.u11 = ById("RAAnbunit11").value;
	if (ById("RAAnbunit12").value>0) params.u12 = ById("RAAnbunit12").value;
	
	}else {
	 params.u3 = ById("RAAnbunit3").value;
	
	}
  	t.actionRAA.disabled=true;
        t.actionREN.disabled=true;
        t.actionREE.disabled=true;
	t.statutRAA.innerHTML = "<i><b>En cours de traitement....</b></i>";
	new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
	              method: "post",
	              parameters: params,
	              loading: true,
	              onSuccess: function (transport) {
	                  var t = myBO.Attaque;  
	                  var rslt = transport;
	                  if (rslt.ok) {
			   var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
	                   var ut = unsafeWindow.unixtime();
	                   var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
	                   for(i = 0; i <= unitsarr.length; i++){
	                   	if(params["u"+i]){
	                  	unitsarr[i] = params["u"+i];
	                  	}
	                   }
	                   var resources=new Array();
	                   resources[0] = params.gold;
	                   for(i=1; i<=4; i++){
	                  	resources[i] = params["r"+i];
	                   }
	                   var currentcityid =  t.sourceCity.id;
	                   unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
	                   unsafeWindow.update_seed(rslt.updateSeed)
	                   if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
	                   
	                   for(var i=0;i<iused.length;i++){
			    Seed.items["i"+iused[i]]=parseInt(Seed.items["i"+iused[i]])-1;unsafeWindow.ksoItems[iused[i]].subtract();
			   }		
	                   if (typemarche==2) var typeattaque="Renfort envoy&eacute;"; 
	                   if (typemarche==4) var typeattaque="Attaque envoy&eacute;e"; 
	                   if (typemarche==3) {var typeattaque="Eclaireur envoy&eacute;";  ById("RAAnbunit3").value=0; }
     	 		   t.statutRAA.innerHTML = "<center><font size='3px'><b>"+typeattaque+"</b></font></center>";
	                   t.actionRAA.disabled=false;
	                   t.actionREE.disabled=false;
      			   t.actionREN.disabled=false;	
      			   t.clickRAACitySourceSelect(t.sourceCity);
	                  } else {
			    t.statutRAA.innerHTML ="<font color=red size='3px'><b>Erreur, merci de recommencer !<b></font>";
			     if (rslt.msg) {
			       t.statutRAA.innerHTML +="<br><font color=black size='2px'>" + rslt.msg +"</font>";
	         	     
	                     t.actionRAA.disabled=false;
      			     t.actionREN.disabled=false;
      			     t.actionREE.disabled=false;
      			     }else{
      			      t.statutRAA.innerHTML +="<br>Erreur...</font>";
         	     	      t.actionRAA.disabled=false;
     			     t.actionREN.disabled=false;
      			     t.actionREE.disabled=false;
      			     }
	                  }
	                  },
	                  onFailure: function () {
	                    var t = myBO.Attaque;
	                    t.statutRAA.innerHTML ="<font color=red size='3px'><b>Erreur, merci de recommencer !<b></font>";
	                    t.actionRAA.disabled=false;
      			    t.actionREN.disabled=false;
      			    t.actionREE.disabled=false;
	                  }
	          });
    },
    estimerRes: function() {
     var t = myBO.Attaque;
     var x1 = parseInt(t.sourceCity.x);
     var x2 = parseInt(t.destinationCityx.value);
     var y1 = parseInt(t.sourceCity.y);
     var y2 = parseInt(t.destinationCityy.value);
     var dist = distance (x1, y1, x2, y2);
     ById("BOEstimationD").innerHTML = '<b>' + dist + '</b>&nbsp;<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ t.destinationCityx.value +','+ t.destinationCityy.value +')</a>';     
     for (r=1; r<13; r++){
        var m = estETA(dist, r, t.sourceCity.id,4);
        ById("BOEstimationTT"+r).innerHTML = "<b>" + m.etaStr + "</b>";
        var m = estETA(dist, r, t.sourceCity.id,2);
        ById("BOEstimationTZ"+r).innerHTML = "<b>" + m.friendEtaStr + "</b>";
     }
    var closestDist=999999;
	var closestLoc=null;
	var closestNum=1;
	for (var c=0; c<Cities.numCities; c++){
	var city = Cities.cities[c];
	var dist=distance(city.x,city.y,x2,y2);
	if(dist<closestDist) {
	 closestDist=dist;
	 closestLoc=city.x +','+ city.y;
	 closestNum=c+1;
	}
	}
	ById("BOVilleProche").innerHTML='<input type="submit" value="'+closestNum+'" class="castleBut castleButNon">'		
    },
    SelectFavoris:function() {
      var t = myBO.Attaque;
      if (t.listeFavoris.value!='') {
       var valeur=t.listeFavoris.value;
       var x=valeur.substr(0, valeur.lastIndexOf(','));
       var y=valeur.substr(valeur.lastIndexOf(',')+1, valeur.length);
       t.destinationCityx.value = x;
       t.destinationCityy.value = y;
      }
      t.estimerRes();
     },
      chercherFavoris: function() {
      var t = myBO.Attaque;
      var myA = getMyAlliance ();
      if (myA[0]!=0) {
         var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
         params.perPage = 100;
         params.allianceId = myA[0];
             new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
   	        method: "post",
   	        parameters: params,
   	        onSuccess: function (rslt) {
   	          if (rslt.ok){
   	           var z=0;
   	           var m="";
   	           for (var i=0; i<rslt.results.length; i++){
        		      p = rslt.results[i];
   		      if (p.userId != 0){
   		       for (var c=0; c<p.cities.length; c++){
   		         if (Seed.player.name!=p.displayName) {
   		          m += "<option value='" + p.cities[c].xCoord + ","+ p.cities[c].yCoord+"'>" + p.displayName + " - Ville " + (c+1) + " - " + p.cities[c].xCoord + "," + p.cities[c].yCoord+"</option>";
   		         }
   		       }  	       
   		      }
         	    }
         	    t.listeFavoris.innerHTML="<option value=''>Selectionner...</option>"+m;
   	          }
   	        },
   	        onFailure: function (rslt) {
   	          t.listeFavoris.innerHTML="<option>Erreur</option>";
   	        },
       	});
      } else {
        t.listeFavoris.innerHTML="<option>Pas d'alliance !</option>";
      }
  },
   SaveCoordsOptions: function(x,y) {
       Options.Xrenfort = x;
       Options.Yrenfort = y;
       saveOptions ();
  },
  clickRAACitySourceSelect : function (city){
     var t = myBO.Attaque;
     if (t.sourceCity!=city) {
      t.sourceCity = city; 
     }
     var m="";
     m="<table cellspacing=0 cellpadding=0 width=80%><tr><td colspan=2>Unit&eacutee</tr>";
     var cityID = 'city'+ t.sourceCity.id;
     for (r=1; r<13; r++){   
       m += '<tr><td align=right><img title="'+unsafeWindow.unitcost['unt'+r][0]+'" height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td>\
             <td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="RAAdestunit'+r+'" type=text size=7 readonly value="'+parseInt(Seed.units[cityID]['unt'+r])+'">&nbsp;\
             <input type=button value=">" id="RAApdestunit'+r+'"  style="border:1px solid black;height:16px;font-size:11px;"></td></tr>';
     }
     m += "</table>";
     ById("RAAstatsource").innerHTML = m;
        var knt = new Array();
        for (k in Seed.knights['city' + t.sourceCity.id]){
               		if (Seed.knights['city' + t.sourceCity.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.sourceCity.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["politicsKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["combatKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["intelligenceKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"]){
               			knt.push ({
               				Name:   Seed.knights['city' + t.sourceCity.id][k]["knightName"],
               				Combat:	Seed.knights['city' + t.sourceCity.id][k]["combat"],
               				ID:	Seed.knights['city' + t.sourceCity.id][k]["knightId"],
               			});
               		}
               }
               knt = knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);}); 
               ById('RAApiKnight').innerHTML="";
               var o = document.createElement("option");
     	       o.text = uW.g_js_strings.modal_attack.dchooseknightd;
     	       o.value = 0;
               ById("RAApiKnight").options.add(o);
               for (k in knt){
            			if (knt[k]["Name"] !=undefined){
        	    			var o = document.createElement("option");
        	    			o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +')')
        	    			o.value = knt[k]["ID"];
        	    			ById("RAApiKnight").options.add(o);
            			}
         }
      if (ById('RAApiKnight').options.length>0) {
       ById('RAApiKnight').selectedIndex=1;
      } 
      
      var itemlist=[55,57,931,932];
      for(var i=0;i<itemlist.length;i++){
        ById('BOitemSpan_'+itemlist[i]).innerHTML = unsafeWindow.ksoItems[itemlist[i]].count;
      }
     for (r=1; r<13; r++){
       ById("RAApdestunit"+r).addEventListener ('click', function() {
         var nomcha=this.id.replace("RAApdest","RAAdest");
         var nomcha2=this.id.replace("RAApdestunit","RAAnbunit");
         ById(nomcha2).value=0; 
         var e=1;
         var f=unsafeWindow.unixtime();
         if(Seed.playerEffects.aurasExpire){if(Seed.playerEffects.aurasExpire>f){e=1.15}}
	 if(Seed.playerEffects.auras2Expire){if(Seed.playerEffects.auras2Expire>f){e=1.3}}
         var l_elem=ById("BOitem_931");
	 if(l_elem&&l_elem.checked&&parseInt(Seed.items["i931"])>0){	        e+=0.25;	 }
	 var l_elem=ById("BOitem_932");
	 if(l_elem&&l_elem.checked&&parseInt(Seed.items["i932"])>0){	        e+=0.5;     }
         var niveauPointRall=parseInt(getCityBuilding (t.sourceCity.id, 12).maxLevel); // 12=Point de ralliement
         var maxtroupe=parseInt(niveauPointRall*10000*e);
         if (niveauPointRall==11) maxtroupe=parseInt(150000*e);
         if (niveauPointRall==12) maxtroupe=parseInt(200000*e);
         var q=uW.cm.ThroneController.effectBonus(66);
         maxtroupe=Math.round(maxtroupe*(1+q/100));
         var nbunitto=0;
         for (r=1; r<13; r++) {
           nbunitto+=parseIntNan(ById("RAAnbunit"+r).value);
	 }
         var libre = parseIntNan(maxtroupe - nbunitto);
         if (ById(nomcha).value>=libre) {
           ById(nomcha2).value = libre;
         }  else {
           ById(nomcha2).value= ById(nomcha).value;
         }
        }, false);
     }
     if (t.sourceCity!=city) {
           for (r=1; r<13; r++){
            ById("RAAnbunit"+r).value="0";
           }
     } else {
          for (r=1; r<13; r++){
              if (ById("RAAnbunit"+r).value=="") ById("RAAnbunit"+r).value="0";
              if (ById("RAAdestunit"+r).value=="") ById("RAAdestunit"+r).value="0";
                if (parseInt(ById("RAAnbunit"+r).value)>parseInt(ById("RAAdestunit"+r).value)) {
                 ById("RAAnbunit"+r).value="0";
                }
           }
     }
     t.estimerRes();
   },
}  
myBO.Gifts = {
  gifts : null,
  myDiv : null,
  doList : [], 
  doServer : 0,
  accepting : false,
  cont : null,
  init : function (){
    var t = myBO.Gifts;
    t.cont = document.createElement('div');

  },
  getContent : function (){
    var t = myBO.Gifts;
    return t.cont;
  },
  show : function (){
  var t = myBO.Gifts;
      t.cont.innerHTML = '<TABLE cellpadding=0 cellspacing=0  width=100%><TR><TR><TD width=10 align=left><a href=https://apps.facebook.com/kingdomsofcamelot/?page=choosegift title="SendGifts" target="_blank">Envoyez des KDO</a></td><TD width=200></td><TD align=center><INPUT id="pasubGifts" type=submit value="Cadeaux en attente" \></td><TD width=200 align=right></td></tr></table><HR>\
          <DIV id=giftDiv style="width:100%; min-height:300px; height:100%">';
      ById('pasubGifts').addEventListener ('click', t.e_clickedGifts, false);
      if (!Options.giftDomains.valid)
      Options.giftDomains.list[getServerId()] = unsafeWindow.domainName;
  },
  hide : function (){
  },
  e_clickedGifts : function  (){
    var t = myBO.Gifts;
    if (t.accepting){
      ById('pasubGifts').value = 'Recherche les cadeaux en attente';
      ById('giftDiv').innerHTML+= '<BR><SPAN class=boldRed>Annulee.</span>';
      t.accepting = false;
      return;
    }
    ById('giftDiv').innerHTML = 'R&eacute;cup&eacute;ration des cadeaux Facebook en cours ...<br><br>Attention votre navigateur va se bloquer, c\'est normal...<br><br>Si votre navigateur vous alerte : - Le script ne reponds pas - appuyez sur Continuer. Merci';
    
    t.fetchGiftsPage (gotGiftsPage);
    function gotGiftsPage(rslt){
      if (rslt.errMsg){
        ById('giftDiv').innerHTML += rslt.errMsg;
        return;
      }
      t.gifts = rslt;
      if (!Options.giftDomains.valid && t.gifts.length>0){
        t.ajaxGetGiftData (t.gifts[0], listGifts, function (){});
        return;
      }
      listGifts();
    }
    
    function listGifts (){
 
      var m = '<DIV class=boStat><CENTER>CADEAUX EN ATTENTE ('+ t.gifts.length +' trouv&eacute;)</center></div>';
      if (t.gifts.length<1){
        ById('giftDiv').innerHTML = m + '<BR><BR><CENTER>Aucun cadeau disponible !</center>';
        return;
      }
      m += '<TABLE class=pbTab align=center><TR><TD align=right>Serveur : </td><TD>'
        + htmlSelector (Options.giftDomains.list, getServerId(), 'id=pbGiftServers') +'</td></tr>\
          <TR><TD align=right>Suppression :</td><TD>'
        + htmlSelector ({y:'Toujours', e:'Seulement si erreur', n:'Jamais'}, Options.giftDelete, 'id=pbGiftDel')
        + '</td></tr><TR><TD>&nbsp</td><TD width=250><INPUT type=submit id=pbGiftDo value="Accepter">\
        &nbsp; <SPAN id=pbGiftNone class=boldRed></span></td></tr></table><HR><TABLE class=pbTab><TR valign=top><TD>\
        <INPUT id=pbGiftButAll type=submit value="Tous" style="width:100%; margin-bottom:5px"><BR><INPUT id=pbGiftButNone type=submit value="Aucun"></td>\
        <TD width=10></td><TD><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabLined width=80%>\
        <TBODY id=pbGiftTbody style="height:250px; overflow:auto; display:block;">\
        <TR style="font-weight:bold; background:white"><TD>Cadeau</td><TD>Date</td><TD>Depuis (server)</td><TD width=20></td></tr>';
      t.gifts.sort (function (a,b){ 
          var x = a.gift.localeCompare (b.gift);
          if (x != 0)
            return x;
          return a.args.da.localeCompare(b.args.da);
          });
      for (var i=0; i<t.gifts.length; i++){
        var giftName = t.gifts[i].gift;
        if (t.gifts[i].args.si == 9)
          giftName += ' (Daily)';
        var date = t.gifts[i].args.da.substr(0,4) +'-'+ t.gifts[i].args.da.substr(4,2) +'-'+ t.gifts[i].args.da.substr(6,2);
        m += '<TR><TD><INPUT type=checkbox id=pbgchk_'+ i +'> &nbsp;'+ giftName +'</td><TD>'+ date +'</td>\
              <TD>'+ t.gifts[i].giver +' ('+ t.gifts[i].args.exs +')</td></tr>';
      }
      ById('giftDiv').innerHTML = m + '</tbody></table></td></tr></table>';
      ById('pbGiftDo').addEventListener ('click', t.getErDone, false);
      ById('pbGiftButAll').addEventListener ('click', t.e_butAll, false);
      ById('pbGiftButNone').addEventListener ('click', t.e_butNone, false);
    }
  },

  e_butAll : function (){
    var t = myBO.Gifts;
    for (var i=0; i<t.gifts.length; i++)
      ById('pbgchk_'+i).checked = true;
  },
  
  e_butNone : function (){
    var t = myBO.Gifts;
    for (var i=0; i<t.gifts.length; i++)
      ById('pbgchk_'+i).checked = false;
  },
  
  getErDone : function (){
    var t = myBO.Gifts;
    t.doList = [];
    ById('pbGiftNone').innerHTML = '';
    Options.giftDelete = ById('pbGiftDel').value;
    for (var i=0; i<t.gifts.length; i++){
      if (ById('pbgchk_'+i).checked)
        t.doList.push (t.gifts[i]);
    }
    if (t.doList.length==0){
      ById('pbGiftNone').innerHTML = 'None Selected!';
      return;
    }
    t.doServer = ById('pbGiftServers').value;
    t.accepting = true;
    ById('pasubGifts').value = 'Stopper';
    ById('giftDiv').innerHTML = '<DIV id=acpDiv style="height:400px; max-height:400px; overflow-y:auto"><B>Acceptation de '+ t.doList.length +' cadeaux:</b><BR></div>';    
    t.acceptNext ();
  },

    
  allDone : function (msg){
    var t = myBO.Gifts;
    ById('acpDiv').innerHTML += '<BR><BR>' + msg;
    ById('pasubGifts').value = 'Recherche les cadeaux en attente';
    t.accepting = false;
  },
  
    
  acceptNext : function (){
    var t = myBO.Gifts;
    var gift = t.doList.shift();
    if (gift == null){
      t.allDone ('Acceptation des cadeaux termin&eacute;e.');
      return;
    }
    var acpDiv = ById('acpDiv');
    var curDiv = document.createElement ('div');
    acpDiv.appendChild (curDiv);
    curDiv.innerHTML = '<B>'+ gift.gift +'</b> depuis '+ gift.giver +' du '+ gift.args.da.substr(0,4) +'-'+ gift.args.da.substr(4,2) +'-'+ gift.args.da.substr(6,2) +': ';    
    var statSpan = document.createElement ('span');
    curDiv.appendChild (statSpan);
    statSpan.innerHTML = ' Lecture ';
    t.ajaxGetGiftData (gift, gotGiftData, progress);
    
    function progress (m){
      if (t.accepting)
        statSpan.innerHTML += ' '+m;
    }
        
    function gotGiftData (rslt){
      if (!t.accepting)
        return;
      if (rslt.ok){
        statSpan.innerHTML += ' &nbsp; Accept&eacute;.';
        t.ajaxAcceptGift (gift, t.doServer, doneAccepting);
        return;
      }
        
      if (rslt.feedback)
        msg = '<B>'+ rslt.feedback + '</b>';
      else
        msg = '<SPAN class=boldRed>ERROR: '+ rslt.ajaxErr +'</span>';
      if (rslt.del && Options.giftDelete!='n'){
        t.deleteGift (gift);  
        msg += ' Supprim&eacute;.';
      }
      curDiv.removeChild (statSpan);
      curDiv = document.createElement ('div');
      curDiv.className = 'indent25';
      acpDiv.appendChild (curDiv);
      curDiv.innerHTML = msg;
      t.acceptNext ();  
    }
    
    function doneAccepting (rslt){
      if (!t.accepting)
        return;
      var msg = '<font color=#0b0>OK</font>.';
      if (!rslt.ok)
        msg = '<SPAN class=boldRed>'+ rslt.msg +'</span>';
      statSpan.innerHTML = msg;
      if (Options.giftDelete=='y'){
        statSpan.innerHTML += ' &nbsp; supprim&eacute;.';
        t.deleteGift (gift);      
      }
      t.acceptNext ();  
    }
  },
  ajaxAcceptGift : function (gift, serverId, notify){
    var url;
    var pargs = {};  
    if (gift.dat.ver == 1){
      url = gift.dat.url;
      pargs.giftId = gift.dat.giftId;
      pargs.hasExistingServer = 1;
      pargs.serverid = serverId;
      pargs.go = 'Next';
      GM_AjaxPost (url, pargs, ver1GotPost, 'Accept');
    } else {
      var i = gift.dat.url.indexOf('src/');
      url = gift.dat.url.substr(0,i) +'src/ajax/claimgift.php?wcfbuid='+ gift.dat.wcfbuid;        
      pargs = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      pargs.fb_sig_ext_perms = unescape(pargs.fb_sig_ext_perms);
      pargs.ver = '2';
      pargs.selectedS = serverId;
      pargs.giftinviteid = gift.dat.giftId;
      GM_AjaxPost (url, pargs, ver2GotPost, 'Accept');
     }     
    function ver1GotPost (rslt){
      if (rslt == null){
        notify ({ok:false, msg:"AJAX Error"});
        return;
      }
      var m = /<div class=\'nm\'>(.*?)<\/div/im.exec(rslt);
      if (m)
        notify ({ok:false, msg: 'Got '+ m[1]});
      else
        notify ({ok:true, msg:'OK'});
    }
    function ver2GotPost (rslt){
      if (rslt == null){
        notify ({ok:false, msg:"AJAX Error"});
        return;
      }
      rslt = eval ('('+ rslt +')');
      if (rslt.ok)
        rslt.msg = 'OK';
      notify (rslt);
    }
  },
  deleteGift : function (gift){
    var pargs = {};  
    for (var i=0; i<gift.inputs.length; i++){
        pargs[gift.inputs[i].name] = gift.inputs[i].value;
    }
    GM_AjaxPost (window.location.protocol+'//www.facebook.com/ajax/reqs.php?__a=1', pargs, gotAjaxPost, 'Delete');
    function gotAjaxPost (p){
    }
  },
 ajaxGetGiftData : function (gift, notify, progress, DELETE){
     var t = Tabs.Gifts;
     gift.dat = {};
     GM_AjaxGet (gift.submit, null, got1, 'Page 1');        
         
     function got1 (page){
        if (page == null)
         notify ({ajaxErr:'COMM Error - page 1'});
       progress ('1');
 	  page = page.htmlSpecialCharsDecode();
       var m = page.match (/form action="(.*?)"/im);
       if (m == null)
         notify ({ajaxErr:'PARSE Error - page 1'});
 	  var url = m[1].htmlSpecialCharsDecode(); 
 	    url = unescape(url);
         url = url.replace ('\\/', '/', 'g');
 		url = url.replace (/\\u00253A/g, ':');
 		url = url.replace (/\\u00257C/g, '|');
 	  var signed_request = /signed_request" value="(.*?)"/im.exec (page);
 	  var opts = [];
 	  opts.signed_request = signed_request[1];
       GM_AjaxPost (url, opts, got2, 'Page 2');        
     }
    function got2 (page){
       if (page == null)
         notify ({ajaxErr:'COMM Error - page 2'});
       progress ('2');
       var m = /top.location.href = \"(.*?)\"/im.exec (page);
       if (m == null)
        m = /top.location.replace\(\"(.*?)\"\)/im.exec (page);
       if (m==null)
         notify ({ajaxErr:'PARSE Error - page 2'});
       var url = m[1].htmlSpecialCharsDecode(); 
       GM_AjaxGet (url, '', got3, 'Page 3');        
     }
   function got3 (page){
       if (page == null)
         notify ({ajaxErr:'COMM Error - page 3'});
       progress ('3');
 	  page = page.htmlSpecialCharsDecode();
 	  var m = page.match (/form action="(.*?)"/im);
       if (m == null)
         notify ({ajaxErr:'PARSE Error - page 3'});
       var url = m[1].htmlSpecialCharsDecode();
 	  url = unescape(url);
 	  url = url.replace ('\\/', '/', 'g');
 	  var signed_request = /signed_request" value="(.*?)"/im.exec (page);
 	  var opts = [];
 	  opts.signed_request = signed_request[1];
       GM_AjaxPost (url, opts, got4, 'Page 4');        
     }
     function got4 (page){
       if (page == null)
         notify ({ajaxErr:'COMM Error - page 4'});
       progress ('4');
 	  page = page.htmlSpecialCharsDecode();
 	  
      var m = page.match (/src='(.*?)'/im);
       if (m == null) m = page.match (/form action="(.*?)"/im);
       if (m == null) notify ({ajaxErr:'PARSE Error - page 4'});
       var url = m[1].htmlSpecialCharsDecode();
       url = url.replace (/lang=.*?&/, 'lang=en&');  
 	  url = url.replace ('\\/', '/', 'g');	
 	  url = url.replace ('&amp;', '&', 'g');
 	  url = url.replace ('" + (new Date()).getTime() + "', (new Date()).getTime());
       gift.dat.url = url;
       var signed_request = /signed_request" value="(.*?)"/im.exec (page);
        var opts = [];
        opts.signed_request = signed_request[1];
        GM_AjaxPost (url, opts, got5, 'Page 5');       
     }
     function got5 (page){
       if (page == null)
         notify ({ajaxErr:'COMM Error - page 5'});
       progress ('5');
 	  page = page.htmlSpecialCharsDecode();
       var m = /<div class=\'giftreturned\'>(.*?)<\/div/im.exec(page);
       if (m != null){
         notify ({feedback:m[1], del:true});
         return;
       }
       var m = /(We were unable to find your gift.*?)</im.exec(page);
       if (m != null){
         notify ({feedback:m[1], del:true});
         return;
       }
       var m = /(Unable to get the list of your friends.*?)</im.exec(page);
       if (m != null){
         notify ({feedback:m[1]});
         return;
       }
       var m = /(Facebook says you are not friends.*?)</im.exec(page);
       if (m != null){
         notify ({feedback:m[1], del:true});
         return;
       }
             
       var regexp = /<option value='(.*?)'.*?>(.*?)</img ;
       var m;
       while ( (m = regexp.exec (page)) != null){
         if (m[1] != 'noserver')
           Options.giftDomains.list[m[1]] = m[2];  
       }
       Options.giftDomains.valid = true;
       if (page.indexOf('ver:2') >= 0){
         m = /giftinviteid:(.*?),/im.exec(page);
         if (m == null)
           notify ({ajaxErr:'PARSE Error (ver:2, giftinviteid not found) - page 5'});
         gift.dat.giftId = m[1];
         gift.dat.ver = 2;    
       } else {
         m = /name='giftId' value='(.*?)'/im.exec(page);
         if (m == null){
           notify ({ajaxErr:'PARSE Error (ver:1, giftId not found) - page 5'});
           return;
         }
         gift.dat.giftId = m[1];
         gift.dat.ver = 1;
       }
       notify ({ok:true});
     }
  },
  fetchGiftsPage : function (notify){
      var gifts = [];
      GM_AjaxGet (window.location.protocol+'//www.facebook.com/games', '', parseGiftsPage, 'FB Gifts Page');
      
      function parseGiftsPage  (p){
        if (p == null)
          notify ({errMsg:'Ajax Comm Error'});
        p = p.htmlSpecialCharsDecode();
   

        var t = myBO.Gifts;
        var gifts = [];
        
        try {    
          var m = p.split ('<form');  
 
          for (var i=0; i<m.length; i++){
              if ( m[i].indexOf('Kingdoms of Camelot')<0)
              continue
            var mm = m[i].match( /facebook.com\/.*\">(.*?)<\/a><\/span>.*?(?:voudrait t'offrir un (.*?) dans)/im );          
            //if (mm==null) 
            //  mm = m[i].match( /facebook.com\/.*\">(.*?)<\/span><\/span><\/a>.*?(?:voudrait t'offrir un (.*?) dans)/im );
            if (mm==null) 
               mm = m[i].match( /facebook.com\/.*\">(.*?)<\/a><\/span>.*?(?:would like to give you a (?:gift of|)(.*?) in |Here is a(.*?)you can use)/im );
	     /*if (mm==null)
              mm = m[i].match( /facebook.com\/.*\">(.*?)<\/span><\/span><\/a>.*?(?:would like to give you a (?:gift of|)(.*?) in |Here is a(.*?)you can use)/im ); 
             if (mm==null)
              mm = m[i].match( /facebook.com\/.*\">(.*?)<\/span><\/span><\/a>.*?(?:would like to give you a (?:gift of|)(.*?) in |Here is a(.*?)you can use)/im ); 
             if (mm==null)
              mm = m[i].match( /facebook.com\/.*\">(.*?)<\/a><\/span>.*?(?:in (.*?). Hurry and claim your Gift before it expires!)/im ); 
            if (mm==null)
              mm = m[i].match( /facebook.com\/.*\">(.*?)<\/a><\/span>.*?(?:in (.*?). Hurry and claim)/im );    
              
  	    if (mm==null)
             mm = m[i].match( /appRequestBodyNewA\">(.*) sent an you an invitation to use Kingdoms of Camelot/im );
            if (mm==null)
  	      mm = m[i].match( /appRequestBodyNewA\">(.*) utiliser Kingdoms of Camelot/im );
  	    if (mm==null)
  	      mm = m[i].match( /appRequestBodyNewA\">(.*) Hurry and claim/im );
	    if (mm==null)
		mm = m[i].match( /appRequestBodyNewA\">(.*) Hurry and claim/im );  
		*/
if (mm==null) 
  mm = m[i].match( /appRequestBodyNewA.*<strong>(.*?)<\/strong>.*would like to give you a gift of (.*?) in/im);  
 
 if (mm==null) 
    continue;
 

          var giver = mm[1];
	  if (mm[2])
            var gift = mm[2].trim();
            
            // get all inputs ...  (name, value, type)          
 	  var inps = [];
          var args = {};  
          var inpsub = null;    
        
          var ins = m[i].match (/<input.*?>/igm);
          for (var ii=0; ii<ins.length; ii++){
            var it = {};
            mm = /value=\"(.*?)\"/im.exec(ins[ii]);
			if (mm==null)
				continue;
            it.value = mm[1];
            mm = /name=\"(.*?)\"/im.exec(ins[ii]);
            if (mm==null)
				continue;
            it.name = mm[1];
            mm = /type=\"(.*?)\"/im.exec(ins[ii]);
            if (mm==null)
				continue;
            it.type = mm[1];
            if (it.type=='submit' && it.name!='actions[reject]'){
              it.name = eval ('"'+ it.name +'"');          
              mm = /actions\[(.*?)\]/im.exec(it.name);
              inpsub = mm[1].replace('\\/', '/', 'g');
              inpsub = inpsub.replace('&amp;', '&', 'g');
              var a = inpsub.split ('&');
              for (var iii=0; iii<a.length; iii++){
                var aa = a[iii].split ('=');
                if (aa[0]=='da' || aa[0]=='si'){
                  args[aa[0]] = unescape(aa[1]);
                } else if (aa[0] == 'ex') {
                  var s = unescape(aa[1]).split ('|');
                  for (var iiii=0; iiii<s.length; iiii++){
                    var ss = s[iiii].split(':');
                    if (ss[0] == 's')
                      args.exs = ss[1];
					else
					  args[ss[0]] = ss[1];
                  }
                }
              }
	     if(args.gid) gift = unsafeWindow.itemlist['i'+args.gid].name;
            } else {
              inps.push (it);
            }
          }
         
          if (args.da)
            gifts.push ({giver:giver, gift:gift, args:args, submit:inpsub, inputs:inps});
        }
        notify (gifts);
      } catch (e) {
        notify ({errMsg:"Error parsing Facebook gift page "+ e});
      }
    }
  },
}

myBO.Crest = {
  cont : null,
  rallypointlevel:null,
  error_code: 0,
  knt:{},
  init : function (){
   var t = myBO.Crest;
   t.cont = document.createElement('div');
   var t = myBO.Crest;
	if (CrestOptions.Running == true) {
		setInterval(t.FirstRound,10000);
		setInterval(t.ThirdRound,10000);
		setInterval(t.sendCrestReport, 1*60*1000);
	}
	
	setTimeout(function() { 
	AddSubTabLink('AutoTS', t.toggleCrestState, 'pbautotstab');
	
	if (CrestOptions.Running == false)
	 updatebotbutton("AutoTS - OFF", 'pbautotstab');
	else
	 updatebotbutton("AutoTS - ON", 'pbautotstab');
	 
	},500);
	
	return this.cont;	
},
  getContent : function (){
        var t = myBO.Crest;
        return t.cont;
  },
  show : function() {
   var t = myBO.Crest;
    mainPop2.div.style.width = 800 + 'px';
    if (Options.widescreen==true) mainPop2.div.style.width = Colors.TabWidth + 'px';
    var selbut=0;
    var m = '<DIV id=pbTowrtDivF class=boStat>ATTAQUE AUTOMATIQUE TERRES SAUVAGES / ARMOIRIES</div><TABLE id=pbcrestfunctions width=100% height=0% class=pbTab><TR align="center">';
     if (CrestOptions.Running == false) {
	       m += '<TD><INPUT id=Cresttoggle type=submit value="Armoiries - OFF"></td>';
	       
} else {
	       m += '<TD><INPUT id=Cresttoggle type=submit value="Armoiries - ON"></td>';
	       
    }
    m += '<TD><INPUT id=CrestHelp type=submit value="Aide"></td></table>';
    m += '<TD><INPUT id=pbsendcrestreport type=checkbox '+ (Options.crestreport?' CHECKED':'') +'\> Envoyer un rapport toute les ';
    m += '<INPUT id=pbsendcrestreportint value='+ Options.CrestMsgInterval +' type=text size=3 \> heures &nbsp; <input type=button value="Envoyer un rapport maintenant" id=bosendreportnow></td></table>';
    m += '<DIV id=pbOpt class=boStat>OPTIONS ARMOIRIES #1</div><TABLE id=pbcrestopt	 width=100% height=0% class=pbTab><TR align="center"></table>';
    m += '<DIV style="margin-bottom:10px;"><b>Depuis la ville : </b> <span id=crestcity></span></div>';
    m += '<TABLE class=pbTab><TR><TD><b>TS</b> : X:<INPUT id=pbcrestx type=text size=3 maxlength=3 value="'+CrestOptions.X+'"</td>';
    m += '<TD>Y:<INPUT id=pbcresty type=text size=3 maxlength=3 value="'+CrestOptions.Y+'"</td></tr></table>';
    m += '<TABLE class=pbTab><TR><TD><b>1. </b></td><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_30.png></td><TD><INPUT id=R1MM type=text size=5 maxlength=6 value="'+CrestOptions.R1MM+'"></td><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_30.png></td><TD><INPUT id=R1Scout type=text size=5 maxlength=6 value="'+CrestOptions.R1Scout+'"></td>';
    m += '</td><TD></td><TD><TD><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_30.png></td><TD><INPUT id=R1Ball type=text size=5 maxlength=6 value="'+CrestOptions.R1Ball+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_30.png></td><TD><INPUT id=R1Cat type=text size=5 maxlength=6 value="'+CrestOptions.R1Cat+'"</td></tr>';
    m += '<TR><TD><b>2. </b></td><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_30.png></td><TD><INPUT id=R2MM type=text size=5 maxlength=6 value="'+CrestOptions.R2MM+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_30.png></td><TD><INPUT id=R2Scout type=text size=5 maxlength=6 value="'+CrestOptions.R2Scout+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_30.png></td><TD><INPUT id=R2Pike type=text size=5 maxlength=6 value="'+CrestOptions.R2Pike+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_30.png></td><TD><INPUT id=R2Sword type=text size=5 maxlength=6 value="'+CrestOptions.R2Sword+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_30.png></td><TD><INPUT id=R2Arch type=text size=5 maxlength=6 value="'+CrestOptions.R2Arch+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_30.png></td><TD><INPUT id=R2Ball type=text size=5 maxlength=6 value="'+CrestOptions.R2Ball+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_30.png></td><TD><INPUT id=R2Ram type=text size=5 maxlength=6 value="'+CrestOptions.R2Ram+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_30.png></td><TD><INPUT id=R2Cat type=text size=5 maxlength=6 value="'+CrestOptions.R2Cat+'"</td>';
    m += '</tr><tr><td></td><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_30.png></td><TD><INPUT id=R2Wag type=text size=5 maxlength=6 value="'+CrestOptions.R2Wag+'"</td></tr></table>';
    m += '<DIV id=pbOpt class=boStat>OPTIONS ARMOIRIES #2</div><TABLE id=pbcrestopt	 width=100% height=0% class=pbTab><TR align="center"></table>';
    m += '<DIV style="margin-bottom:10px;"><b>Depuis la ville : </b> <span id=Crest1City></span></div>';
    m += '<TABLE class=pbTab><TR><TD><b>TS</b> : X:<INPUT id=pbcrestx1 type=text size=3 maxlength=3 value="'+CrestOptions.CX+'"</td>';
    m += '<TD>Y:<INPUT id=pbcresty1 type=text size=3 maxlength=3 value="'+CrestOptions.CY+'"</td></tr></table>';
    m += '<TABLE class=pbTab><TR><TD><b>1.</b> </td><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_30.png></td><TD><INPUT id=R3MM type=text size=5 maxlength=6 value="'+CrestOptions.R3MM+'"></td><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_30.png></td><TD><INPUT id=R3Scout type=text size=5 maxlength=6 value="'+CrestOptions.R3Scout+'"></td>';
    m += '</td><TD></td><TD><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_30.png></td><TD><INPUT id=R3Ball type=text size=5 maxlength=6 value="'+CrestOptions.R3Ball+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_30.png></td><TD><INPUT id=R3Cat type=text size=5 maxlength=6 value="'+CrestOptions.R3Cat+'"</td></tr>';
    m += '<TR><TD><b>2.</b> </td><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_30.png></td><TD><INPUT id=R4MM type=text size=5 maxlength=6 value="'+CrestOptions.R4MM+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_30.png></td><TD><INPUT id=R4Scout type=text size=5 maxlength=6 value="'+CrestOptions.R4Scout+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_30.png></td><TD><INPUT id=R4Pike type=text size=5 maxlength=6 value="'+CrestOptions.R4Pike+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_30.png></td><TD><INPUT id=R4Sword type=text size=5 maxlength=6 value="'+CrestOptions.R4Sword+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_30.png></td><TD><INPUT id=R4Arch type=text size=5 maxlength=6 value="'+CrestOptions.R4Arch+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_30.png></td><TD><INPUT id=R4Ball type=text size=5 maxlength=6 value="'+CrestOptions.R4Ball+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_30.png></td><TD><INPUT id=R4Ram type=text size=5 maxlength=6 value="'+CrestOptions.R4Ram+'"</td>';
    m += '<TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_30.png></td><TD><INPUT id=R4Cat type=text size=5 maxlength=6 value="'+CrestOptions.R4Cat+'"</td>';
    m += '</tr><tr><td></td><TD><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_30.png></td><TD><INPUT id=R4Wag type=text size=5 maxlength=6 value="'+CrestOptions.R4Wag+'"</td></tr></table>';
    t.cont.innerHTML = m;
    ById('bosendreportnow').addEventListener('click', function() {
	t.sendCrestReportNow();
	
	}, false);
    ById('pbsendcrestreport').addEventListener('change', function(){
		Options.crestreport = ById('pbsendcrestreport').checked;
		saveOptions();
	}, false);
    	ById('pbsendcrestreportint').addEventListener('change', function(){
		Options.CrestMsgInterval = parseInt(ById('pbsendcrestreportint').value);
		saveOptions();
	}, false);

    for (var i=0;i<Seed.cities.length;i++){
		if (CrestOptions.CrestCity == Seed.cities[i][0]){
			selbut=i;
			break;
		}
    }
    t.tcp = new CdispCityPicker ('crestcityselect', ById('crestcity'), true, t.clickCitySelect, selbut);
    
    if (CrestOptions.CrestCity == 0) {
    	CrestOptions.CrestCity = t.tcp.city.id
    	saveCrestOptions();
    }

	for (var i=0;i<Seed.cities.length;i++){
		if (CrestOptions.Crest1City == Seed.cities[i][0]){
			selbut=i;
			break;
		}
	}

    t.tcpto = new CdispCityPicker ('crestcitys', ById('Crest1City'), true, t.clickcityselect, selbut);
    
    if (CrestOptions.Crest1City == 0) {
    	CrestOptions.Crest1City = t.tcpto.city.id
    	saveCrestOptions();
    }

	ById('Cresttoggle').addEventListener('click', t.toggleCrestState, false);
    ById('crestcity').addEventListener('click', function(){CrestOptions.CrestCity = t.tcp.city.id; saveCrestOptions();} , false);
    ById('CrestHelp').addEventListener('click', function(){t.helpPop();} , false);
    ById('pbcrestx').addEventListener('change', function(){CrestOptions.X = ById('pbcrestx').value; saveCrestOptions();} , false);
    ById('pbcresty').addEventListener('change', function(){CrestOptions.Y = ById('pbcresty').value; saveCrestOptions()} , false);
    ById('R1MM').addEventListener('change', function(){CrestOptions.R1MM = ById('R1MM').value; saveCrestOptions()} , false);
    ById('R1Scout').addEventListener('change', function(){CrestOptions.R1Scout = ById('R1Scout').value; saveCrestOptions()} , false);
    ById('R1Ball').addEventListener('change', function(){CrestOptions.R1Ball = ById('R1Ball').value; saveCrestOptions()} , false);
    ById('R1Cat').addEventListener('change', function(){CrestOptions.R1Cat = ById('R1Cat').value; saveCrestOptions()} , false);
    ById('R2MM').addEventListener('change', function(){CrestOptions.R2MM = ById('R2MM').value; saveCrestOptions()} , false);
    ById('R2Scout').addEventListener('change', function(){CrestOptions.R2Scout = ById('R2Scout').value; saveCrestOptions()} , false);
    ById('R2Pike').addEventListener('change', function(){CrestOptions.R2Pike = ById('R2Pike').value; saveCrestOptions()} , false);
    ById('R2Sword').addEventListener('change', function(){CrestOptions.R2Sword = ById('R2Sword').value; saveCrestOptions()} , false);
    ById('R2Arch').addEventListener('change', function(){CrestOptions.R2Arch = ById('R2Arch').value; saveCrestOptions()} , false);
    ById('R2Ball').addEventListener('change', function(){CrestOptions.R2Ball = ById('R2Ball').value; saveCrestOptions()} , false);
    ById('R2Ram').addEventListener('change', function(){CrestOptions.R2Ram = ById('R2Ram').value; saveCrestOptions()} , false);
    ById('R2Cat').addEventListener('change', function(){CrestOptions.R2Cat = ById('R2Cat').value; saveCrestOptions()} , false);
    ById('R2Wag').addEventListener('change', function(){CrestOptions.R2Wag = ById('R2Wag').value; saveCrestOptions()} , false);	
    ById('Crest1City').addEventListener('click', function(){CrestOptions.Crest1City = t.tcpto.city.id; saveCrestOptions();} , false);
    ById('pbcrestx1').addEventListener('change', function(){CrestOptions.CX = ById('pbcrestx1').value; saveCrestOptions();} , false);
    ById('pbcresty1').addEventListener('change', function(){CrestOptions.CY = ById('pbcresty1').value; saveCrestOptions()} , false);
    ById('R3MM').addEventListener('change', function(){CrestOptions.R3MM = ById('R3MM').value; saveCrestOptions()} , false);
    ById('R3Scout').addEventListener('change', function(){CrestOptions.R3Scout = ById('R3Scout').value; saveCrestOptions()} , false);
    ById('R3Ball').addEventListener('change', function(){CrestOptions.R3Ball = ById('R3Ball').value; saveCrestOptions()} , false);
    ById('R3Cat').addEventListener('change', function(){CrestOptions.R3Cat = ById('R3Cat').value; saveCrestOptions()} , false);
    ById('R4MM').addEventListener('change', function(){CrestOptions.R4MM = ById('R4MM').value; saveCrestOptions()} , false);
    ById('R4Scout').addEventListener('change', function(){CrestOptions.R4Scout = ById('R4Scout').value; saveCrestOptions()} , false);
    ById('R4Pike').addEventListener('change', function(){CrestOptions.R4Pike = ById('R4Pike').value; saveCrestOptions()} , false);
    ById('R4Sword').addEventListener('change', function(){CrestOptions.R4Sword = ById('R4Sword').value; saveCrestOptions()} , false);
    ById('R4Arch').addEventListener('change', function(){CrestOptions.R4Arch = ById('R4Arch').value; saveCrestOptions()} , false);
    ById('R4Ball').addEventListener('change', function(){CrestOptions.R4Ball = ById('R4Ball').value; saveCrestOptions()} , false);
    ById('R4Ram').addEventListener('change', function(){CrestOptions.R4Ram = ById('R4Ram').value; saveCrestOptions()} , false);
    ById('R4Cat').addEventListener('change', function(){CrestOptions.R4Cat = ById('R4Cat').value; saveCrestOptions()} , false);
    ById('R4Wag').addEventListener('change', function(){CrestOptions.R4Wag = ById('R4Wag').value; saveCrestOptions()} , false);
  },
  
  helpPop : function (){
        var helpText = '<BR>L\'onglet ARMOIRIES est fait pour attaquer continuellement et automatiquement une Terre sauvage.<BR>';
        helpText += 'Cela attaque en 2 vague, abandonne la terre si n&eacute;cessaire et recommence.<BR>';
        helpText += 'V&eacute;rifier que vous avez 1 place de libre dans votre chateau pour une terre sauvage &agrave; conquerir.<BR>';
        helpText += 'Remplisser les coordonnees d\'une Terre Sauvage et les troupes et appuyer sur ON !.<BR><BR>';
        helpText += 'Nombre de troupes (KOC WIKI):<BR>';
        helpText += '<A target="_tab" href="http://koc.wikia.com/wiki/Wilderness">Plus d\'informations sur Koc Wikia</a>';
        helpText += '<TABLE width=100%><TR><TD>Level</td><TD>Vague 1</td><TD>Vague 2</td><TD>Pertes</td><TD>Emp. Min</td></tr>';
        helpText += '<TR><TD>1</td><TD>n/a</td><TD>160 MM</td><TD>12 MM</td><TD>0</td></tr>';
        helpText += '<TR><TD>1</td><TD>n/a</td><TD>80 archers</td><TD>Aucune</td><TD>1+</td></tr>';
        helpText += '<TR><TD>2</td><TD>5 MM</td><TD>130 archers</td><TD>1ere Vague</td><TD>2+</td></tr>';
        helpText += '<TR><TD>3</td><TD>10 MM</td><TD>520 archers</td><TD>1ere Vague</td><TD>3+</td></tr>';
        helpText += '<TR><TD>4</td><TD>20 MM</td><TD>1600 archers</td><TD>1ere Vague</td><TD>4+</td></tr>';
        helpText += '<TR><TD>5</td><TD>50 MM</td><TD>2200 archers</td><TD>1ere Vague</td><TD>6+</td></tr>';
        helpText += '<TR><TD>6</td><TD>100 MM</td><TD>3000 archers</td><TD>1ere Vague</td><TD>7+</td></tr>';
        helpText += '<TR><TD>7</td><TD>150 MM</td><TD>6000 archers</td><TD>1ere Vague</td><TD>8+</td></tr>';
        helpText += '<TR><TD>8</td><TD>299 MM + 1Bal</td><TD>9000 archers + 900 Bal</td><TD>1ere Vague + 1 Archer</td><TD>9+</td></tr>';
        helpText += '<TR><TD>9</td><TD>599 MM + 1Bal</td><TD>13000 archers + 900 Bal</td><TD>1ere Vague + 2 Archer</td><TD>10</td></tr>';
        helpText += '<TR><TD>10</td><TD>1199 MM + 1Cat</td><TD>35000 archers + 2500 Cat</td><TD>1ere Vague + 6 Archer + 50 Cat</td><TD>10</td></tr></table><br><br>';
    
    var pop = new CPopup ('ArmoiriesHelp', 0, 0, 585, 400, true);
    pop.centerMe (mainPop.getMainDiv());  
    pop.getMainDiv().innerHTML = helpText;
    pop.getTopDiv().innerHTML = '<CENTER><B>Aide sur l\'attaque des terres sauvages - Armoiries</b></center>';
    pop.show (true);
  },
  
  toggleCrestState: function(obj){
	var t = myBO.Crest;
	obj = ById('Cresttoggle');
        if (CrestOptions.Running == true) {
            CrestOptions.Running = false;
            if (obj) obj.value = "Armoiries - OFF";
            updatebotbutton('AutoTS - OFF', 'pbautotstab');
            saveCrestOptions();
        }
        else {
            CrestOptions.Running = true;
            setInterval(t.FirstRound,10000);
	    setInterval(t.ThirdRound,10000);
	    setInterval(t.sendCrestReport, 1*60*1000);
             if (obj) obj.value = "Armoiries - ON";
            updatebotbutton('AutoTS - ON', 'pbautotstab');
            for (crest in Options.Creststatus){
            		owned = Seed.items['i'+crest];
            		if (owned == undefined) owned=0;
            		Options.Creststatus[crest] = owned;
            		Options.CrestLevel = 0;
            		Options.CrestType = 0;
            		Options.Crest1Count = 0;
            		Options.Crest2Count = 0;
            		Options.Crest1Level = 0;
            		Options.Crest1Type = 0;
            		Options.Crest3Count = 0;
            		Options.Crest4Count = 0;
					}
            var now = new Date().getTime()/1000.0;
            now = now.toFixed(0);
            Options.LastCrestReport = now;
            saveCrestOptions();
        }
    },
    
   sendCrestReportNow: function(){
    	var t = myBO.Crest;
    	var now = new Date().getTime()/1000.0;
        now = now.toFixed(0);   	
    	var total = 0;
    	var wildtype = '';
    	switch (Options.CrestType) {
    			  case '10' : wildtype = unsafeWindow.g_js_strings.commonstr.grassland;break;
    			  case '11' : wildtype = unsafeWindow.g_js_strings.commonstr.lake;break;
    			  case '20' : wildtype = unsafeWindow.g_js_strings.commonstr.woods;break;
    			  case '30' : wildtype = unsafeWindow.g_js_strings.commonstr.hills;break;
    			  case '40' : wildtype = unsafeWindow.g_js_strings.commonstr.mountain;break;
    			  case '50' : wildtype = unsafeWindow.g_js_strings.commonstr.plain;break;
    	} 
    	var wildtype2 = '';
    	switch (Options.Crest1Type) {
    			  case '10' : wildtype2 = unsafeWindow.g_js_strings.commonstr.grassland;break;
    			  case '11' : wildtype2 = unsafeWindow.g_js_strings.commonstr.lake;break;
    			  case '20' : wildtype2 = unsafeWindow.g_js_strings.commonstr.woods;break;
    			  case '30' : wildtype2 = unsafeWindow.g_js_strings.commonstr.hills;break;
    			  case '40' : wildtype2 = unsafeWindow.g_js_strings.commonstr.mountain;break;
    			  case '50' : wildtype2 = unsafeWindow.g_js_strings.commonstr.plain;break;
    	}
        var message = 'Rapports Armoiries sur auto attaque de TS : %0A';
        message += '%0A Armoiries gagnees (depuis '+ Options.CrestMsgInterval +' heure) sur ArmoiriesAuto #1 : niveau '+Options.CrestLevel+' '+wildtype+' et/ou ArmoiriesAuto #2 :'+Options.Crest1Level+' '+wildtype2+'%0A';
        for (crest in Options.Creststatus){
        	owned = Seed.items['i'+crest];
        	if (owned == undefined) owned=0;
	      	if ( (owned - Options.Creststatus[crest]) > 0) message+= '<DIV><B>' + unsafeWindow.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A </b></div>';
	      	else message+= unsafeWindow.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A';
	    	total += (owned - Options.Creststatus[crest]);
	    	Options.Creststatus[crest] = owned;
      	}
    	message += '%0A Nombre d\armoiries gagnees : '+ total +'%0A';
	message += '%0A 1. Nombre de premieres vagues envoyees ArmoiriesAuto #1 : '+ Options.Crest1Count +'%0A';
    	message += '2. Nombre de deuxiemes vagues envoyees ArmoiriesAuto #1 : '+ Options.Crest2Count +'%0A';
	message += '%0A 3. Nombre de premieres vagues envoyees ArmoiriesAuto #2 : '+ Options.Crest3Count +'%0A';
    	message += '4. Nombre de deuxiemes vagues envoyees ArmoiriesAuto #2: '+ Options.Crest4Count +'%0A';
    	Options.Crest1Count = 0;
    	Options.Crest2Count = 0;
    	Options.Crest3Count = 0;
    	Options.Crest4Count = 0;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.emailTo = Seed.player['name'];
      params.subject = "Rapports Armoiries";
      params.message = message;
      params.requestType = "COMPOSED_MAIL";
      new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
          method: "post",
          parameters: params,
          onSuccess: function (message) {
              var rslt = eval("(" + message.responseText + ")");
              if (rslt.ok) {
              		Options.LastCrestReport = now;
              } else {
              }
          },
          onFailure: function () {
          },
      });
      saveOptions();
    },   
   sendCrestReport: function(){
    	var t = myBO.Crest;
    
    	if(!Options.crestreport || !CrestOptions.Running) return;
    	var now = new Date().getTime()/1000.0;
        now = now.toFixed(0);
        if (now < (parseInt(Options.LastCrestReport)+(Options.CrestMsgInterval*60*60))) return;
    	
    	var total = 0;
    	var wildtype = '';
    	switch (Options.CrestType) {
    			  case '10' : wildtype = unsafeWindow.g_js_strings.commonstr.grassland;break;
    			  case '11' : wildtype = unsafeWindow.g_js_strings.commonstr.lake;break;
    			  case '20' : wildtype = unsafeWindow.g_js_strings.commonstr.woods;break;
    			  case '30' : wildtype = unsafeWindow.g_js_strings.commonstr.hills;break;
    			  case '40' : wildtype = unsafeWindow.g_js_strings.commonstr.mountain;break;
    			  case '50' : wildtype = unsafeWindow.g_js_strings.commonstr.plain;break;
    	} 
    	var wildtype2 = '';
    	switch (Options.Crest1Type) {
    			  case '10' : wildtype2 = unsafeWindow.g_js_strings.commonstr.grassland;break;
    			  case '11' : wildtype2 = unsafeWindow.g_js_strings.commonstr.lake;break;
    			  case '20' : wildtype2 = unsafeWindow.g_js_strings.commonstr.woods;break;
    			  case '30' : wildtype2 = unsafeWindow.g_js_strings.commonstr.hills;break;
    			  case '40' : wildtype2 = unsafeWindow.g_js_strings.commonstr.mountain;break;
    			  case '50' : wildtype2 = unsafeWindow.g_js_strings.commonstr.plain;break;
    	}
        var message = 'Rapports Armoiries sur auto attaque de TS : %0A';
        message += '%0A Armoiries gagnees (depuis '+ Options.CrestMsgInterval +' heure) sur ArmoiriesAuto #1 : niveau '+Options.CrestLevel+' '+wildtype+' et/ou ArmoiriesAuto #2 :'+Options.Crest1Level+' '+wildtype2+'%0A';
        for (crest in Options.Creststatus){
        	owned = Seed.items['i'+crest];
        	if (owned == undefined) owned=0;
	      	if ( (owned - Options.Creststatus[crest]) > 0) message+= '<DIV><B>' + unsafeWindow.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A </b></div>';
	      	else message+= unsafeWindow.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A';
	    	total += (owned - Options.Creststatus[crest]);
	    	Options.Creststatus[crest] = owned;
      	}
    	message += '%0A Nombre d\armoiries gagnees : '+ total +'%0A';
	message += '%0A 1. Nombre de premieres vagues envoyees ArmoiriesAuto #1 : '+ Options.Crest1Count +'%0A';
    	message += '2. Nombre de deuxiemes vagues envoyees ArmoiriesAuto #1 : '+ Options.Crest2Count +'%0A';
	message += '%0A 3. Nombre de premieres vagues envoyees ArmoiriesAuto #2 : '+ Options.Crest3Count +'%0A';
    	message += '4. Nombre de deuxiemes vagues envoyees ArmoiriesAuto #2: '+ Options.Crest4Count +'%0A';
    	Options.Crest1Count = 0;
    	Options.Crest2Count = 0;
    	Options.Crest3Count = 0;
    	Options.Crest4Count = 0;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.emailTo = Seed.player['name'];
      params.subject = "Rapports Armoiries";
      params.message = message;
      params.requestType = "COMPOSED_MAIL";
      new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
          method: "post",
          parameters: params,
          onSuccess: function (message) {
              var rslt = eval("(" + message.responseText + ")");
              if (rslt.ok) {
              		Options.LastCrestReport = now;
              } else {
              }
          },
          onFailure: function () {
          },
      });
      saveOptions();
    },
    getAtkKnight : function(cityID){
     var t = myBO.Crest;
     t.knt = new Array();
     for (k in Seed.knights[cityID]){
     		if (Seed.knights[cityID][k]["knightStatus"] == 1 && Seed.leaders[cityID]["resourcefulnessKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["politicsKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["combatKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["intelligenceKnightId"] != Seed.knights[cityID][k]["knightId"]){
     			t.knt.push ({
     				Name:   Seed.knights[cityID][k]["knightName"],
     				Combat:	parseInt(Seed.knights[cityID][k]["combat"]),
     				ID:		Seed.knights[cityID][k]["knightId"],
     			});
     		}
     }
     t.knt = t.knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
  },
  getRallypointLevel: function(cityId){
    var t = myBO.Crest;
    for (var o in Seed.buildings[cityId]){
  	var buildingType = parseInt(Seed.buildings[cityId][o][0]);
  	var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
  	if (buildingType == 12) t.rallypointlevel=parseInt(buildingLevel);
     }
  },
 
  FirstRound: function(){
      var t = myBO.Crest;
      var buzy = false;
     
     
      
      if (!CrestOptions.Running) return;
      cityID = 'city' + CrestOptions.CrestCity;
      var abandon=0;
      for (var k in Seed.wilderness[cityID] ){
           if (Seed.wilderness[cityID][k]['xCoord']==CrestOptions.X && Seed.wilderness[cityID][k]['yCoord']==CrestOptions.Y && t.error_code!=401) {
             t.abandonWilderness(Seed.wilderness[cityID][k]['tileId'],Seed.wilderness[cityID][k]['xCoord'],Seed.wilderness[cityID][k]['yCoord'],CrestOptions.CrestCity);
           }
      }
      if (parseInt(Seed.units[cityID]['unt2']) < CrestOptions.R1MM || parseInt(Seed.units[cityID]['unt3']) < CrestOptions.R1Scout || parseInt(Seed.units[cityID]['unt10']) < CrestOptions.R1Ball || parseInt(Seed.units[cityID]['unt12']) < CrestOptions.R1Cat || parseInt(Seed.units[cityID]['unt2']) < CrestOptions.R2MM || parseInt(Seed.units[cityID]['unt3']) < CrestOptions.R2Scout || parseInt(Seed.units[cityID]['unt4']) < CrestOptions.R2Pike || parseInt(Seed.units[cityID]['unt5']) < CrestOptions.R2Sword || parseInt(Seed.units[cityID]['unt6']) < CrestOptions.R2Arch || parseInt(Seed.units[cityID]['unt10']) < CrestOptions.R2Ball || parseInt(Seed.units[cityID]['unt11']) < CrestOptions.R2Ram || parseInt(Seed.units[cityID]['unt12']) < CrestOptions.R2Cat || parseInt(Seed.units[cityID]['unt9']) < CrestOptions.R2Wag) {
       //actionLog("AutoTS","1-1 : Pas assez de troupe disponible sur la ville");
       return;
      }
      for (var k in Seed.queue_atkp[cityID]){
        if (Seed.queue_atkp[cityID][k]['toXCoord']==CrestOptions.X && Seed.queue_atkp[cityID][k]['toYCoord']==CrestOptions.Y) { 
         buzy=true;
         var now=unixTime ();
         var retr=Seed.queue_atkp[cityID][k]['returnUnixTime'];
         var alors=retr-now;
         if (alors<0) {
            actionLog("AutoTS","1-1 : Erreur dans les marches --> suppression - on continue");
            delete Seed.queue_atkp[cityID][k];
            buzy=false;
         }
         
        }
      }
      if (!buzy)  {
        CrestOptions.RoundOne=true;
        CrestOptions.RoundTwo=true;
        saveCrestOptions();
      }
      if(!CrestOptions.RoundOne) return;
      if (CrestOptions.X==0 && CrestOptions.Y==0) {
       return;
      }
      if ((CrestOptions.R2MM+CrestOptions.R2Scout+CrestOptions.R2Pike+CrestOptions.R2Sword+CrestOptions.R2Arch+CrestOptions.R2Ball+CrestOptions.R2Ram+CrestOptions.R2Cat+CrestOptions.R2Wag)==0) {
       //actionLog("AutoTS","1-1 : Pas de troupe programme en 1-2 --> STOP");
       return;
      }
      if (CrestOptions.R1MM == 0 && CrestOptions.R1Scout == 0 && CrestOptions.R1Ball==0 && CrestOptions.R1Cat==0){
      actionLog("AutoTS","1-1 : Pas de troupe programme --> on passe a la deuxieme vague directement !");
      CrestOptions.RoundOne = false;
      saveCrestOptions();
      setTimeout (function(){t.SecondRound();}, 1000);
      return;
      }
      
      t.getAtkKnight(cityID);
      slots=0;
       for (z in Seed.queue_atkp[cityID]){
             slots++;
       }
       if  (Seed.queue_atkp[cityID].toSource() == "[]") slots=0;
       t.getRallypointLevel(cityID);     
       if(t.rallypointlevel == 12) t.rallypointlevel = 11;
       
       
       if ((t.rallypointlevel) <= slots) {
         actionLog("AutoTS","1-1 : Point de ralliement complet -> STOP ");
         return;
       }
       if  (t.knt.toSource() == "[]") {
        actionLog("AutoTS","1-1 : Pas de chevalier dispo -> STOP ");
        return;
       }  
       var kid = t.knt[0].ID;
       var now = new Date().getTime()/1000.0;
       now = now.toFixed(0)
		
	          
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  		params.cid=CrestOptions.CrestCity;
  		params.type=4;
  	    params.kid=kid;
  		params.xcoord = CrestOptions.X;
  		params.ycoord = CrestOptions.Y;
        if (now < (parseInt(CrestOptions.lastRoundTwo) + 300)) { 
        	params.u2= (CrestOptions.R1MM / 10);
        	params.u2 = params.u2.toFixed(0);	
        	if (params.u2 < (CrestOptions.R1MM / 10)) params.u2++;
        }	
 		else params.u2= CrestOptions.R1MM;
 		params.u3=CrestOptions.R1Scout;
  		params.u10=CrestOptions.R1Ball;
  		params.u12=CrestOptions.R1Cat;
    		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
  		         method: "post",
  		         parameters: params,
  		         loading: true,
  		         onSuccess: function (transport) {
  		         var rslt = eval("(" + transport.responseText + ")");
  		         if (rslt.ok) {
  		         var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
  		         var ut = unsafeWindow.unixtime();
  		         var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
  		         var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
  		         for(i = 0; i <= unitsarr.length; i++){
  		         	if(params["u"+i]){
  		         	unitsarr[i] = params["u"+i];
  		         	}
  		         }
  		         var currentcityid = params.cid;
  		         unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
  		         if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
  		         CrestOptions.RoundOne = false;
  		         Options.Crest1Count++;
  		         Options.CrestLevel = rslt.tileLevel;
  		         Options.CrestType = rslt.tileType;
  		         saveCrestOptions();
  		         actionLog("AutoTS","1-1 : Envoi OK sur " +CrestOptions.X+","+CrestOptions.Y);
  		         setTimeout (function(){t.SecondRound();}, 5000);
       		         } else {
       		         actionLog("AutoTS","1-1 : Envoi ERREUR sur " +CrestOptions.X+","+CrestOptions.Y+"<br>"+ transport.responseText );
       		         }
  		         },
  		         onFailure: function (transport) {
  		                 actionLog("AutoTS","1-1 : Envoi ERREUR sur " +CrestOptions.X+","+CrestOptions.Y+"<br>"+ transport.responseText );
  		         }
  		 });
  		 
   },
    SecondRound: function(){
      var t = myBO.Crest;
      if (!CrestOptions.Running || !CrestOptions.RoundTwo) return;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      cityID = 'city' + CrestOptions.CrestCity;
      if (parseInt(Seed.units[cityID]['unt2']) < CrestOptions.R2MM || parseInt(Seed.units[cityID]['unt3']) < CrestOptions.R2Scout ||parseInt(Seed.units[cityID]['unt4']) < CrestOptions.R2Pike || parseInt(Seed.units[cityID]['unt5']) < CrestOptions.R2Sword || parseInt(Seed.units[cityID]['unt6']) < CrestOptions.R2Arch || parseInt(Seed.units[cityID]['unt10']) < CrestOptions.R2Ball  || parseInt(Seed.units[cityID]['unt11']) < CrestOptions.R2Ram || parseInt(Seed.units[cityID]['unt12']) < CrestOptions.R2Cat || parseInt(Seed.units[cityID]['unt9']) < CrestOptions.R2Wag) {
       //actionLog("AutoTS","1-2 : Pas assez de troupe disponible sur la ville");
       return;
      }
      t.getAtkKnight(cityID);
      slots=0;
       for (z in Seed.queue_atkp[cityID]){
             slots++;
       }
       if  (Seed.queue_atkp[cityID].toSource() == "[]") slots=0;
       t.getRallypointLevel(cityID);
       if(t.rallypointlevel == 12) t.rallypointlevel = 11;      
       if ((t.rallypointlevel) <= slots) {
         actionLog("AutoTS","1-2 : Point de ralliement complet -> STOP ");
         return;
       }
       if  (t.knt.toSource() == "[]") {
        actionLog("AutoTS","1-2 : Pas de chevalier dispo -> STOP ");
        return;
       } 
       var kid = t.knt[0].ID;
 	params.cid=CrestOptions.CrestCity;
	params.type=4;
	params.kid=kid;
	params.xcoord = CrestOptions.X;
	params.ycoord = CrestOptions.Y;
	params.u2=CrestOptions.R2MM;
	params.u3=CrestOptions.R2Scout;
	params.u4=CrestOptions.R2Pike;
	params.u5=CrestOptions.R2Sword;
	params.u6=CrestOptions.R2Arch;
	params.u10=CrestOptions.R2Ball;
	params.u11=CrestOptions.R2Ram;
	params.u12=CrestOptions.R2Cat;
	params.u9=CrestOptions.R2Wag;
	new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
  		         method: "post",
  		         parameters: params,
  		         loading: true,
  		         onSuccess: function (transport) {
  		         var rslt = eval("(" + transport.responseText + ")");
  		         if (rslt.ok) {
  		         var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
  		         var ut = unsafeWindow.unixtime();
  		         var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
  		         var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
  		         for(i = 0; i <= unitsarr.length; i++){
  		         	if(params["u"+i]){
  		         	unitsarr[i] = params["u"+i];
  		         	}
  		         }
  		         var currentcityid = params.cid;
  		         unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
  		         if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
  		         CrestOptions.RoundTwo = false;
               var now = new Date().getTime()/1000.0;
               now = now.toFixed(0);
               CrestOptions.lastRoundTwo = now;
               Options.Crest2Count++;
  	       saveCrestOptions();
  	       actionLog("AutoTS","1-2 : Envoi OK -> " +CrestOptions.X+","+CrestOptions.Y);
  		      
               } else {
               
               if (rslt.user_action=="marchCaptcha") {
	        actionLog("AutoTS","<font color=red>1-2 : Envoi ERREUR -> CAPTCHA</font>");
	        return;
	       }
	       actionLog("AutoTS","1-2 : Envoi ERREUR -> Recommence dans 5s sur " +CrestOptions.X+","+CrestOptions.Y+"<br>"+transport.responseText);
               setTimeout (function(){t.SecondRound();}, 5000);
  		         }
  		         },
  		         onFailure: function () {
  		         actionLog("AutoTS","1-2 : Envoi ERREUR sur " +CrestOptions.X+","+CrestOptions.Y+"<br>"+transport.responseText);
  		         }
  		 });
  		 },
  		 
  ThirdRound: function(){
      var t = myBO.Crest;
      var buzy = false;
      if (!CrestOptions.Running) return;
      cityID = 'city' + CrestOptions.Crest1City;
      var abandon=0;
      for (var k in Seed.wilderness[cityID] ){
           if (Seed.wilderness[cityID][k]['xCoord']==CrestOptions.CX && Seed.wilderness[cityID][k]['yCoord']==CrestOptions.CY && t.error_code!=401) {
             t.abandonWilderness(Seed.wilderness[cityID][k]['tileId'],Seed.wilderness[cityID][k]['xCoord'],Seed.wilderness[cityID][k]['yCoord'],CrestOptions.Crest1City);
           }
      }
      if (parseInt(Seed.units[cityID]['unt2']) < CrestOptions.R3MM || parseInt(Seed.units[cityID]['unt3']) < CrestOptions.R3Scout ||parseInt(Seed.units[cityID]['unt10']) < CrestOptions.R3Ball || parseInt(Seed.units[cityID]['unt12']) < CrestOptions.R3Cat || parseInt(Seed.units[cityID]['unt2']) < CrestOptions.R4MM || parseInt(Seed.units[cityID]['unt3']) < CrestOptions.R4Scout || parseInt(Seed.units[cityID]['unt4']) < CrestOptions.R4Pike || parseInt(Seed.units[cityID]['unt5']) < CrestOptions.R4Sword || parseInt(Seed.units[cityID]['unt6']) < CrestOptions.R4Arch || parseInt(Seed.units[cityID]['unt10']) < CrestOptions.R4Ball || parseInt(Seed.units[cityID]['unt11']) < CrestOptions.R4Ram || parseInt(Seed.units[cityID]['unt12']) < CrestOptions.R4Cat || parseInt(Seed.units[cityID]['unt9']) < CrestOptions.R4Wag) {
       //actionLog("AutoTS","2-1 : Pas assez de troupe disponible sur la ville");
       return;
      }
      for (var k in Seed.queue_atkp[cityID]){
        if (Seed.queue_atkp[cityID][k]['toXCoord']==CrestOptions.CX && Seed.queue_atkp[cityID][k]['toYCoord']==CrestOptions.CY) {
                buzy=true;
         var now=unixTime ();
               var retr=Seed.queue_atkp[cityID][k]['returnUnixTime'];
               var alors=retr-now;
               if (alors<0) {
                  actionLog("AutoTS","2-1 : Erreur dans les marches --> suppression - on continue");
                  delete Seed.queue_atkp[cityID][k];
                  buzy=false;
               }
               
        }
      
      }
      if (!buzy)  {
        CrestOptions.RoundThree=true;
        CrestOptions.RoundFour=true;
        saveCrestOptions();
      }
      if(!CrestOptions.RoundThree) return;
            if (CrestOptions.CX==0 && CrestOptions.CY==0) {
             return;
            }
      if ((CrestOptions.R4MM+CrestOptions.R4Scout+CrestOptions.R4Pike+CrestOptions.R4Sword+CrestOptions.R4Arch+CrestOptions.R4Ball+CrestOptions.R4Ram+CrestOptions.R4Cat+CrestOptions.R4Wag)==0) {
            actionLog("AutoTS","2-1 : Pas de troupe programme en 2-2 --> STOP");
            return;
      }
      if (CrestOptions.R3MM == 0 && CrestOptions.R3Scout == 0 && CrestOptions.R3Ball==0 && CrestOptions.R3Cat==0){
      CrestOptions.RoundThree = false;
      actionLog("AutoTS","2-1 : Pas de troupe pregramme --> on passe a la deuxieme vague directement !");
      saveCrestOptions();
      setTimeout (function(){t.FourthRound();}, 1000);
      return;
      }
      
      t.getAtkKnight(cityID);
      slots=0;
       for (z in Seed.queue_atkp[cityID]){
             slots++;
       }
       if  (Seed.queue_atkp[cityID].toSource() == "[]") slots=0;
       t.getRallypointLevel(cityID);     
       if(t.rallypointlevel == 12) t.rallypointlevel = 11;
       if ((t.rallypointlevel) <= slots) {
                actionLog("AutoTS","2-1 : Point de ralliement complet -> STOP ");
                return;
       }
       if  (t.knt.toSource() == "[]") {
        actionLog("AutoTS","2-1 : Pas de chevalier dispo -> STOP ");
        return;
       }   
       var kid = t.knt[0].ID;
       
       var now = new Date().getTime()/1000.0;
       now = now.toFixed(0)
		
	//   if (CrestOptions.R3MM > parseInt(Seed.units[cityID]['unt2']) || CrestOptions.R3Ball > parseInt(Seed.units[cityID]['unt10']) || CrestOptions.R3Cat > parseInt(Seed.units[cityID]['unt12'])){return;}
          
	    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  		params.cid=CrestOptions.Crest1City;
  		params.type=4;
  	    params.kid=kid;
  		params.xcoord = CrestOptions.CX;
  		params.ycoord = CrestOptions.CY;
        if (now < (parseInt(CrestOptions.lastRoundFour) + 300)) { 
        	params.u2= (CrestOptions.R3MM / 10);
        	params.u2 = params.u2.toFixed(0);	
        	if (params.u2 < (CrestOptions.R3MM / 10)) params.u2++;
        }	
  		else params.u2= CrestOptions.R3MM;
  		params.u3= CrestOptions.R3Scout;
  		params.u10=CrestOptions.R3Ball;
  		params.u12=CrestOptions.R3Cat;
  		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
  		         method: "post",
  		         parameters: params,
  		         loading: true,
  		         onSuccess: function (transport) {
  		         var rslt = eval("(" + transport.responseText + ")");
  		         if (rslt.ok) {
  		         var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
  		         var ut = unsafeWindow.unixtime();
  		         var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
  		         var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
  		         for(i = 0; i <= unitsarr.length; i++){
  		         	if(params["u"+i]){
  		         	unitsarr[i] = params["u"+i];
  		         	}
  		         }
  		         var currentcityid = params.cid;
  		         unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
  		         unsafeWindow.update_seed(rslt.updateSeed)
  		         if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
  		         CrestOptions.RoundThree = false;
  		         Options.Crest3Count++;
  		         Options.Crest1Level = rslt.tileLevel;
  		         Options.Crest1Type = rslt.tileType;
  		         saveCrestOptions();
  		         actionLog("AutoTS","2-1 : Envoi OK sur " +CrestOptions.CX+","+CrestOptions.CY);
  		         setTimeout (function(){t.FourthRound();}, 5000);
  		         } else {
  		          actionLog("AutoTS","2-1 : Envoi ERREUR sur " +CrestOptions.CX+","+CrestOptions.CY+"<br>"+ transport.responseText );
       		       
       		         }
  		         },
  		         onFailure: function () {
  		                    actionLog("AutoTS","2-1 : Envoi ERREUR sur " +CrestOptions.CX+","+CrestOptions.CY+"<br>"+ transport.responseText );
  		      }
  		 });
  		 
    }, 
    FourthRound: function(){
      var t = myBO.Crest;
      if (!CrestOptions.Running || !CrestOptions.RoundFour) return;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      cityID = 'city' + CrestOptions.Crest1City;
      if (parseInt(Seed.units[cityID]['unt2']) < CrestOptions.R4MM || parseInt(Seed.units[cityID]['unt3']) < CrestOptions.R4Scout || parseInt(Seed.units[cityID]['unt4']) < CrestOptions.R4Pike || parseInt(Seed.units[cityID]['unt5']) < CrestOptions.R4Sword || parseInt(Seed.units[cityID]['unt6']) < CrestOptions.R4Arch || parseInt(Seed.units[cityID]['unt10']) < CrestOptions.R4Ball || parseInt(Seed.units[cityID]['unt11']) < CrestOptions.R4Ram || parseInt(Seed.units[cityID]['unt12']) < CrestOptions.R4Cat || parseInt(Seed.units[cityID]['unt9']) < CrestOptions.R4Wag) {
           actionLog("AutoTS","2-2 : Pas assez de troupe disponible sur la ville");
             return;
      }
      t.getAtkKnight(cityID);
      slots=0;
       for (z in Seed.queue_atkp[cityID]){
             slots++;
       }
       if  (Seed.queue_atkp[cityID].toSource() == "[]") slots=0;
       t.getRallypointLevel(cityID);
       if(t.rallypointlevel == 12) t.rallypointlevel = 11;      
        if ((t.rallypointlevel) <= slots) {
          actionLog("AutoTS","2-2 : Point de ralliement complet -> STOP ");
          return;
       }
       if  (t.knt.toSource() == "[]") {
        actionLog("AutoTS","2-2 : Pas de chevalier dispo -> STOP ");
        return;
       }  
       var kid = t.knt[0].ID;
  		params.cid=CrestOptions.Crest1City;
  		params.type=4;
  	  	params.kid=kid;
  		params.xcoord = CrestOptions.CX;
  		params.ycoord = CrestOptions.CY;
  		params.u2=CrestOptions.R4MM;
  		params.u3=CrestOptions.R4Scout;
  		params.u4=CrestOptions.R4Pike;
  		params.u5=CrestOptions.R4Sword;
  		params.u6=CrestOptions.R4Arch;
  		params.u9=CrestOptions.R4Wag;
  		params.u10=CrestOptions.R4Ball;
  		params.u11=CrestOptions.R4Ram;
  		params.u12=CrestOptions.R4Cat;
  		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
  		         method: "post",
  		         parameters: params,
  		         loading: true,
  		         onSuccess: function (transport) {
  		         var rslt = eval("(" + transport.responseText + ")");
  		         if (rslt.ok) {
  		         var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
  		         var ut = unsafeWindow.unixtime();
  		         var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
  		         var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
  		         for(i = 0; i <= unitsarr.length; i++){
  		         	if(params["u"+i]){
  		         	unitsarr[i] = params["u"+i];
  		         	}
  		         }
  		         var currentcityid = params.cid;
  		         unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
  		         unsafeWindow.update_seed(rslt.updateSeed);
  		         if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
  		         CrestOptions.RoundFour = false;
               var now = new Date().getTime()/1000.0;
               now = now.toFixed(0);
               CrestOptions.lastRoundFour = now;
               Options.Crest4Count++;
  		         saveCrestOptions();
  		          actionLog("AutoTS","2-2 : Envoi OK -> " +CrestOptions.CX+","+CrestOptions.CY);
               } else {
               actionLog("AutoTS","2-2 : Envoi ERREUR -> Recommence dans 5s sur " +CrestOptions.CX+","+CrestOptions.CY+"<br>"+transport.responseText);
               setTimeout (function(){t.FourthRound();}, 5000);
  		         }
  		         },
  		         onFailure: function () {
  		         actionLog("AutoTS","2-2 : Envoi ERREUR -> " +CrestOptions.CX+","+CrestOptions.CY+"<br>"+transport.responseText);
  		         }
  		 });
 },	 
 abandonWilderness: function(tid,x,y,cid){
      var t = myBO.Crest;
      if (!CrestOptions.Running) return;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      var cityID = cid;
	  var tileid = tid;
      params.tid=tid;
  	  params.cid=cid;
  	  params.x=x;
  		params.y=y;
  		  		
  		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/abandonWilderness.php" + unsafeWindow.g_ajaxsuffix, {
  		         method: "post",
  		         parameters: params,
  		         loading: true,
  		         onSuccess: function (transport) {
  		         var rslt=eval("("+transport.responseText+")");
  		         
  		         
				  if (rslt.ok) {
				  	 t.error_code = 0;
				     CrestOptions.RoundOne = true;
				     CrestOptions.RoundTwo = true;
				     saveCrestOptions();
				      if (rslt.returningMarches) {
				          var cities = Object.keys(rslt.returningMarches);
				          for (var i = 0; i < cities.length; i++) {
				              for (var j = 0; j < rslt.returningMarches[cities[i]].length; j++) {
				                  var cid = cities[i].split("c")[1];
				                  var mid = rslt.returningMarches[cities[i]][j];
				                  var march = Seed.queue_atkp["city" + cid]["m" + mid];
				                  if (march) {
				                      var marchtime = Math.abs(parseInt(march.destinationUnixTime) - parseInt(march.marchUnixTime));
				                      var ut = unsafeWindow.unixtime();
				                      Seed.queue_atkp["city" + cid]["m" + mid].destinationUnixTime = ut;
				                      Seed.queue_atkp["city" + cid]["m" + mid].marchUnixTime = ut - marchtime;
				                      Seed.queue_atkp["city" + cid]["m" + mid].returnUnixTime = ut + marchtime;
				                      Seed.queue_atkp["city" + cid]["m" + mid].marchStatus = 8
				                  }
				              }
				          }
				      }
				      if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
				      
				      if (Object.keys(Seed.wilderness["city" + cityID]).length == 1) {
				          Seed.wilderness["city" + cityID] = []
  		         	  } else{
  		         	  	delete Seed.wilderness["city"+cityID]["t"+tileid];
  		         	  }
   } else {
               		if (rslt.error_code != 401) {
               		    t.error_code = rslt.error_code; 
               			setTimeout (function(){t.abandonWilderness(tid,x,y,cid);}, 5000);
               		}
  		        }
  		         },
   onFailure: function () {}
   });
  }, 
  hide : function (){
    var t = myBO.Crest;
    mainPop2.div.style.width = 750 + 'px';
  },
};
myBO.Stock= {
 cont : null,
 init : function (){
   var t = myBO.Stock;
   unsafeWindow.BOutiliser = t.useItem;
   t.cont = document.createElement('div');
   return t.cont;
 },
   getContent : function (){
       var t = myBO.Stock;
       return t.cont;
     },
     hide : function (){
       var t = myBO.Stock;
       t.state = null;
       clearTimeout (t.displayTimer);
     },
     
     show : function (){  
      var t = myBO.Stock;
      m = "<DIV class=boStat>INVENTAIRE STOCK</div>";
      m += "<div style='max-height:480px; height:480px; overflow-y:auto' id='BOStockContenu'></div>";
      t.cont.innerHTML = m; 
      t.voir();
   },
   voir:function() {
    var t = myBO.Stock;
    var  category = ['','G&eacute;n&eacute;ral','Acc&eacute;l&egrave;re','Combat','Ressources','Coffre','Cour'];
    var puipui={1330:400,1350:600,1411:2000,1455:1350,1474:1000,1465:1350,1351:3000,1445:400,1452:175,1461:90,1371:3500,1391:4500,1427:150,1443:200};
    var puitotal=0;
   var m = "<TABLE border=0 align=center><tr><td colspan=2><b>Article en stock</td><td><b>Quantit&eacute;</td><td><b>Cat&eacute;gorie</td><td></td></tr>";
      var test = Seed.items;
      var e=unsafeWindow.Object.keys(Seed.items);
      var lestock = [];   
      for(var d=0;d<e.length;d++) {
       var h=e[d].split("i")[1];
       var pui=0;
       if(unsafeWindow.itemlist["i"+h] && parseInt(Seed.items[e[d]])>0){
        if ((parseInt(h)<1100 || parseInt(h)>1199) && parseInt(unsafeWindow.itemlist["i"+h].category)>0) {
         if (puipui[h])
          pui=puipui[h] * parseInt(Seed.items[e[d]]);
         m += "<tr><td><img title='"+h+"' id='BOitem"+h+"' onclick='BOutiliser("+h+", this);' src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+Seed.items[e[d]]+"</td><td>"+ category[unsafeWindow.itemlist["i"+h].category] + "</td>";
         m+="<td>"+addCommas(pui)+"</td></tr>"; 
         puitotal=puitotal+pui;
        }
       }
      }
      if (puitotal>0) {
      
      m+="<tr><td colspan=4>TOTAL PUISSANCE DANS L'INVENTAIRE : </td><td><b>"+addCommas(puitotal)+"</tr></table>";
      
      }
    ById('BOStockContenu').innerHTML = m;  
   },
   count:0,
   useItem : function(num, id) {
    var t = myBO.Stock;
    id.src='http://www.ronlohse.com/wait2.gif';
    id.onclick="";
    t.count++;
    unsafeWindow.cm.ItemController.use(num);
     if (t.count>0) {
      t.count=0;
      t.voir();
    } else {
      setTimeout(function(){t.useItem(num,id)},10);
    }
  },
}
myBO.Info = {
  cont : null,
  state : null,
  ModelCity : {},
  init : function (){
    var t = myBO.Info;
    t.cont = document.createElement('div');
    return t.cont;
  },

  getContent : function (){
    var t = myBO.Info;
    return t.cont;
  },

  hide : function (){
    var t = myBO.Info;
  },

  show : function (){
    fortmight = {
      u53: "4",
      u55: "7",
      u60: "1",
      u61: "2",
      u62: "3",
    };
    var t = myBO.Info;
    rownum = 0;
    if (t.state == null){      
      m = '<STYLE>.xtabH {background:#ffffe8; border:none; padding-right: 5px; padding-left: 5px; margin-left:10px; }\
              .xtabHL { background:#ffffe8; border-width: 1px; border-style: none none none solid; padding-right:5px; padding-left:5px; margin-left:10px; }\
              .xtabL { background:none; border-width: 1px; border-style: none none none solid; padding-right:5px; padding-left: 5px; margin-left:10px; }\
              .xtabLine { padding:0px; spacing:0px; height:1px; border-color:black; border-width: 1px; border-style: none none solid none }</style>\
          <DIV style="height:650px; max-height:650px; overflow-y:auto; overflow-x:auto"><DIV class=boStat><b>LES LIENS EXTERNES</div>\
          <table border=0 width=100%><tr><td colspan=2><center><b><a href=http://www.facebook.com/groups/142657062507166/ target=_blank><font size=3>SUPPORT DE LA BOITE SUR FACEBOOK</font></a></td>\
          </tr><tr><td width=50%>La carte koc.dunno.com : <a target=_blank HREF="http://koc.dunno.com/index.sjs?f=KocMapViewer&server_id=' + getServerId() +'">Domaine ' + getServerId() +'</A>\
          </td><td>KOCAttack en francais : <a target=_blank HREF="http://userscripts.org/scripts/show/99495">userscript</A></td></tr>\
          <tr><td>Le site BeWorld KOC Force et Mutinerie <a target=_blank HREF="http://beworld.perso.sfr.fr/KOC/">beworld.perso.sfr.fr</a></td>\
          <td><a target=_blank HREF="http://beworld.perso.sfr.fr/bao/">Le site de la boite a outils</a></td></tr>\
          <tr><td><a HREF="http://beworld.perso.sfr.fr/bao/">La documentation de la boite en cours</a></td><td>Bruitages et son dispo ici : <a target=_blank href="http://www.universal-soundbank.com">www.universal-soundbank.com</a></td></table><br>\
          <DIV class=boStat>INFORMATION UNITEES</div><TABLE align=center cellpadding=1 cellspacing=0>\
          <TR align=center><TD class=xtab></td><TD class=xtabHL colspan=5><B>COUT POUR CONSTRUIRE</b></td><TD class=xtabHL colspan=7><B>STATS</b></td><TD class=xtabHL><B>Entr</b></td></tr>\
          <TR valign=bottom align=right><TD class=xtab></td><TD class=xtabHL>Nour</td><TD class=xtabH>Bois</td><TD class=xtabH>Pierre</td>\
          <TD class=xtabH>Mine</td><TD class=xtabH>Pop</td><TD class=xtabHL>Puis</td><TD class=xtabH>Vie</td><TD class=xtabH>Att</td><TD class=xtabH>Def</td><TD class=xtabH>Vit</td><TD class=xtabH>Rang</td><TD class=xtabH>Charge</td>\
          <TD class=xtabHL>Nour</td></tr>\
          <TR style="height:1px;"><TD style="padding:0px; spacing:0px; height:1px; border-color:black; border-width: 1px; border-style: none none solid none" colspan=14></td></tr>';
      for (ui=1; ui<13; ui++){
        if (++rownum % 2)
          rsty = '';
        else
          rsty = ' style="background: #e8e8e8" ';
        cost = unsafeWindow.unitcost['unt'+ui];
        stats = unsafeWindow.unitstats['unt'+ui];
        food = unsafeWindow.unitupkeeps[ui];
        might = unsafeWindow.unitmight['unt'+ui];
      m += '<TR '+ rsty +'align=right><TD class=xtab align=left><B>'+ cost[0].substr(0,16) +'</b></td><TD class=xtabL>'+ cost[1] +'</td><TD class=xtab>'+ cost[2] +'</td>\
            <TD class=xtab>'+ cost[3] +'</td><TD class=xtab>'+ cost[4] +'</td><TD class=xtab>'+ cost[6] +'</td><TD class=xtabL>'+ might +'</td>\
            <TD class=xtab>'+ stats[0] +'</td><TD class=xtab>'+ stats[1] +'</td><TD class=xtab>'+ stats[2] +'</td><TD class=xtab>'+ stats[3] +'</td>\
            <TD class=xtab>'+ stats[4] +'</td><TD class=xtab>'+ stats[5] +'</td><TD class=xtabL>'+ food +'</td></tr>';

      }
      m += '<TR class=xtabLine><TD colspan=14 class=xtabLine></td></tr>';
      for (k in unsafeWindow.fortcost){
        if (++rownum % 2)
          rsty = '';
        else
          rsty = ' style="background: #e8e8e8" ';
        cost = unsafeWindow.fortcost[k];
        fi = k.substring(3);
        stats = unsafeWindow.fortstats['unt'+fi];
        food = 0;
        might = fortmight['u'+fi];
        name = cost[0].replace ('Defensive','');
        name = name.replace ('Wall-Mounted','');
        m += '<TR '+ rsty +'align=right><TD align=left class=xtab><B>'+ name.substr(0,20) +'</b></td><TD class=xtabL>'+ cost[1] +'</td><TD class=xtab>'+ cost[2] +'</td>\
            <TD class=xtab>'+ cost[3] +'</td><TD class=xtab>'+ cost[4] +'</td><TD class=xtab>'+ cost[6] +'</td><TD class=xtabL>'+ might +'</td>\
            <TD class=xtab>'+ stats[0] +'</td><TD class=xtab>'+ stats[1] +'</td><TD class=xtab>'+ stats[2] +'</td><TD class=xtab>'+ stats[3] +'</td>\
            <TD class=xtab>'+ stats[4] +'</td><TD class=xtab>'+ stats[5] +'</td><TD class=xtabL>'+ food +'</td></tr>';
      }
      m += '<TR class=xtabLine><TD colspan=14 class=xtabLine></td></tr>';
      m += '</table>';
      function _displayrow (name, row){
                    var tot=0;
      			style = ((rownum++ % 2)?'':' style = "background: #e8e8e8"');
      			m += '<TR' + style + '><TD align=right><B>' + name + '</B></td>';
      			for (i=0; i<row.length; i++) {
      				m += ((row[i]==0)?'<td align=right><SPAN class=boldRed>0</SPAN></td>':'<td align=right>'+addCommas(parseInt(row[i]))+'</td>');
      				tot+=parseInt(row[i]);
      				}
      			m += '<td align=right>'+addCommas(tot)+'</td></tr>';
      		}
      		m += '<BR /><DIV class=boStat>VOS RECHERCHES ACTUELLES</div><BR /><SPAN id="Research">&nbsp;</SPAN><BR><DIV class=boStat>ESTIMATIONS - FORMATION DES TROUPES & CONSTRUCTION DES DEFENSES</div>' +
      			'<BR /><TABLE align=center cellpadding=1 cellspacing=0><TABLE align=center cellpadding=1 cellspacing=0><TR align=right><TD></td>';
      		infoRows = [];
      		for (r=0; r<25; r++)
      			infoRows[r] = [];
      		for(i=0; i<Cities.numCities; i++) {
      			cityID = 'city'+ Cities.cities[i].id;
      			m += "<TD align=center valign=bottom width=60px><B>" + Cities.cities[i].name.replace(/ /g, "<BR>").substr(0,10)  + "</B></TD>";
      			getTroopDefTrainEstimates(cityID);
      			infoRows[0][i] = Cities.cities[i].numBarracks;
      			infoRows[1][i] = Cities.cities[i].totLevelsBarracks;
      			infoRows[2][i] = Cities.cities[i].foremanBasePoliticsScore;
      			infoRows[3][i] = Cities.cities[i].marshallCombatScore;
      			infoRows[5][i] = Cities.cities[i].stableLevel;
      			infoRows[6][i] = Cities.cities[i].workshopLevel;
      			infoRows[24][i] = Cities.cities[i].blacksmithLevel;
      			for (var j=1; j<13; j++)
      				infoRows[j+6][i] = ((Cities.cities[i]['Troop'+j+'Time'] > 0)?(3600 / Cities.cities[i]['Troop'+j+'Time']):0);
      			infoRows[19][i] = Cities.cities[i]['Def53Time'];
      			if (infoRows[19][i] > 0)
      				infoRows[19][i] = 3600 / infoRows[19][i];
      			infoRows[20][i] = Cities.cities[i]['Def55Time'];
      			if (infoRows[20][i] > 0)
      				infoRows[20][i] = 3600 / infoRows[20][i];
      			infoRows[21][i] = Cities.cities[i]['Def60Time'];
      			if (infoRows[21][i] > 0)
      				infoRows[21][i] = 3600 / infoRows[21][i];
      			infoRows[22][i] = Cities.cities[i]['Def61Time'];
      			if (infoRows[22][i] > 0)
      				infoRows[22][i] = 3600 / infoRows[22][i];
      			infoRows[23][i] = Cities.cities[i]['Def62Time'];
      			if (infoRows[23][i] > 0)
      				infoRows[23][i] = 3600 / infoRows[23][i];
      		}
      		m += "<td align=center valign=bottom width=60px><b>Totaux</td></tr>";
      		rownum=0;
      		_displayrow ("Nombre de casernes", infoRows[0]);
      		_displayrow ("Niveau des casernes", infoRows[1]);
      		_displayrow ("Contremaitre Politique", infoRows[2]);
      		_displayrow ("Marechal Combat", infoRows[3]);
      		_displayrow ("Niv Ecurie", infoRows[5]);
      		_displayrow ("Niv Atelier", infoRows[24]);
      		_displayrow ("Niv Forgeron", infoRows[6]);      		
      		m += "<TR><TD></TD><TD nowrap align=center colspan="+(Cities.numCities)+"><B>Capacit&eacute; de formation a l'heure</B></TD></TR>";
      		_displayrow ("Ravitailleur", infoRows[7]);
      		_displayrow ("Milicien", infoRows[8]);
      		_displayrow ("Eclaireur", infoRows[9]);
      		_displayrow ("Piquier", infoRows[10]);
      		_displayrow ("Paladin", infoRows[11]);
      		_displayrow ("Archer", infoRows[12]);
      		_displayrow ("Cavalerie", infoRows[13]);
      		_displayrow ("Cavalerie Lourde", infoRows[14]);
      		_displayrow ("Wagon", infoRows[15]);
      		_displayrow ("Baliste", infoRows[16]);
      		_displayrow ("Belier", infoRows[17]);
      		_displayrow ("Catapulte", infoRows[18]);
      		m += "<TR><TD></TD><TD nowrap align=center colspan="+(Cities.numCities)+"><B>Capacit&eacute; de construction a l'heure</B></TD></TR>";
      		_displayrow ("Arbalete", infoRows[19]);
      		_displayrow ("Trebuchet", infoRows[20]);
      		_displayrow ("Piege", infoRows[21]);
      		_displayrow ("Chausse-trape", infoRows[22]);
      		_displayrow ("Palissade", infoRows[23]);
		m += "</TABLE><BR />";
      m += '<BR><DIV class=boStat>CALCULATEUR DISTANCE</div><DIV class=ptentry><TABLE align=center cellpadding=1 cellspacing=0>\
      <TR><TD class=xtab align=right><B>Source : </b></td><TD  class=xtab> X: <INPUT id=calcX type=text\> Y: <INPUT id=calcY type=text\> Or '+unsafeWindow.g_js_strings.commonstr.city+' : <SPAN id=ptloc1></span></td></tr>\
      <TR><TD class=xtab><B>Destination : </b></td><TD class=xtab> X: <INPUT id=calcX2 type=text\> Y: <INPUT id=calcY2 type=text\> Or '+unsafeWindow.g_js_strings.commonstr.city+' <SPAN id=ptloc2></span></td></tr></table>\
      <CENTER><DIV style="width:60%; font-size:14px; border: 1px solid; background-color:white; margin:20px 3px 3px 0px; padding:4px" id=ptdistout></div>\
<div><b>Estimation Temps avec : </b><select id="idETASelect">\
        <option value="0" > -- Selectionner -- </option>\
        <option value="1" >'+unsafeWindow.unitcost['unt1'][0]+'</option>\
        <option value="2" >'+unsafeWindow.unitcost['unt2'][0]+'</option>\
        <option value="3" >'+unsafeWindow.unitcost['unt3'][0]+'</option>\
        <option value="4" >'+unsafeWindow.unitcost['unt4'][0]+'</option>\
        <option value="5" >'+unsafeWindow.unitcost['unt5'][0]+'</option>\
        <option value="6" >'+unsafeWindow.unitcost['unt6'][0]+'</option>\
        <option value="7" >'+unsafeWindow.unitcost['unt7'][0]+'</option>\
        <option value="8" >'+unsafeWindow.unitcost['unt8'][0]+'</option>\
        <option value="9" >'+unsafeWindow.unitcost['unt9'][0]+'</option>\
        <option value="10" >'+unsafeWindow.unitcost['unt10'][0]+'</option>\
        <option value="11" >'+unsafeWindow.unitcost['unt11'][0]+'</option>\
        <option value="12" >'+unsafeWindow.unitcost['unt12'][0]+'</option>\
</select></div><DIV style="width:60%; font-size:14px; border: 1px solid; background-color:white; margin:20px 3px 3px 0px; padding:4px" id=ptETAout></div></center>';
m += '<BR><DIV class=boStat>CARTE DES PROVINCES</div><DIV id=ptProvMap style="height:'+ provMapCoords.imgHeight +'px; width:'+ provMapCoords.imgWidth +'px; background-repeat:no-repeat; background-image:url(\''+ URL_PROVINCE_MAP +'\')"></div></div>';
var bor,ector,kay,bedivere,gawain,percival,galahad,lancelot,arthur,morgana,mordred;
if (Seed.items.i1101){bor=Seed.items.i1101}else{bor=0};
if (Seed.items.i1102){ector=Seed.items.i1102}else{ector=0};
if (Seed.items.i1103){kay=Seed.items.i1103}else{kay=0};
if (Seed.items.i1104){bedivere=Seed.items.i1104}else{bedivere=0};
if (Seed.items.i1105){gawain=Seed.items.i1105}else{gawain=0};
if (Seed.items.i1106){percival=Seed.items.i1106}else{percival=0};
if (Seed.items.i1107){galahad=Seed.items.i1107}else{galahad=0};
if (Seed.items.i1108){lancelot=Seed.items.i1108}else{lancelot=0};
if (Seed.items.i1109){arthur=Seed.items.i1109}else{arthur=0};
if (Seed.items.i1110){morgana=Seed.items.i1110}else{morgana=0};
if (Seed.items.i1111){mordred=Seed.items.i1111}else{mordred=0};
if (Seed.items.i1112){Stag=Seed.items.i1112}else{Stag=0};
if (Seed.items.i1113){Pendragon=Seed.items.i1113}else{Pendragon=0};
if (Seed.items.i1114){Lady=Seed.items.i1114}else{Lady=0};
if (Seed.items.i1115){Merlin=Seed.items.i1115}else{Merlin=0};	
if (Seed.items.i1120){aetherseal=Seed.items.i1120}else{aetherseal=0};	
if (Seed.items.i1121){ysbadden=Seed.items.i1121}else{ysbadden=0};	
if (Cities.cities[1]){ville2="#99EE99";}else{ville2="#EE9999";}
if (Cities.cities[2]){ville3="#99EE99";}else{ville3="#EE9999";}
if (Cities.cities[3]){ville4="#99EE99";}else{ville4="#EE9999";}  
if (Cities.cities[4]){ville5="#99EE99";}else{ville5="#EE9999";}
if (Cities.cities[5]){ville6="#99EE99";}else{ville6="#EE9999";}
if (Cities.cities[6]){ville7="#99EE99";}else{ville7="#EE9999";}
if (Cities.cities[7]){ville8="#99EE99";}else{ville8="#EE9999";}
m += '<style>CAPTION.MYTABLE  {background-color:eeffff;color:black;border-style:solid;border-width:1px;border-color:black;}\
  TABLE.MYTABLE  { \
     font-family:arial;\
     border-collapse:collapse;\
     font-size:10pt;\
     background-color:F5F5F5;\
     width:100%;\
     border-style:solid;\
     border-color:black;\
     border-width:1px;\
  } TH.MYTABLE  {\
     font-size:10pt;\
     color:black;\
     text-align:center;\
     border-style:solid;\
     border-color:black;\
     border-width:1px;\
  } TR.MYTABLE { }\
  TD.MYTABLE {  \
     font-size:10pt;\
     background-color:FFFFE5;\
     color:black;\
     border-style:solid;\
     border-width:1px;\
     text-align:left;\
  }</style>\
<TABLE CLASS="MYTABLE" CELLPADDING=0 CELLSPACING=0>\
    <CAPTION CLASS="MYTABLE">Les armoiries n&eacute;cessaires pour les villes</CAPTION><THEAD >\
      <TR CLASS="MYTABLE">\
        <TH CLASS="MYTABLE">Ville</TH>\
        <TH CLASS="MYTABLE">Besoins 1</TH>\
        <TH CLASS="MYTABLE">Besoins 2</TH>\
        <TH CLASS="MYTABLE">Besoins 3</TH>\
      </TR>\
    </THEAD><TBODY>\
      <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville2+';">'+unsafeWindow.g_js_strings.commonstr.city+' 2</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+ville2+';">Niveau 7 ('+Seed.player.title+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+ville2+';">10 Amis</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+ville2+';">&nbsp;</TD>\
      </TR><TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville3+';">'+unsafeWindow.g_js_strings.commonstr.city+' 3</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+ ( (bor>=4)?"#99EE99":ville3 ) +';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1101.jpg>&nbsp;4 Bor ('+bor+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+ ( (ector>=2)?"#99EE99":ville3 ) +';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1102.jpg>&nbsp;2 Ector ('+ector+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+ ( (kay>=1)?"#99EE99":ville3 ) +';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1103.jpg>&nbsp;1 Kay ('+kay+')</TD>\
      </TR><TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville4+';">'+unsafeWindow.g_js_strings.commonstr.city+' 4</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (kay>=4)?"#99EE99":ville4 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1103.jpg>&nbsp;4 Kay ('+kay+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (bedivere>=3)?"#99EE99":ville4 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1104.jpg>&nbsp;3 Bedivere ('+bedivere+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (gawain>=1)?"#99EE99":ville4 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1105.jpg>&nbsp;1 Gawain ('+gawain+')</TD>\
      </TR>\
      <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville5+';">'+unsafeWindow.g_js_strings.commonstr.city+' 5</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (percival>=4)?"#99EE99":ville5 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1106.jpg>&nbsp;4 Perceval ('+percival+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (galahad>=3)?"#99EE99":ville5 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1107.jpg>&nbsp;3 Galaad ('+galahad+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (lancelot>=2)?"#99EE99":ville5 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1108.jpg>&nbsp;2 Lancelot ('+lancelot+')</TD>\
      </TR>\
      <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville6+';">'+unsafeWindow.g_js_strings.commonstr.city+' 6</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (arthur>=4)?"#99EE99":ville6 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1109.jpg>&nbsp;4 Roi Arthur ('+arthur+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (morgana>=3)?"#99EE99":ville6 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1110.jpg>&nbsp;3 Morgane ('+morgana+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (mordred>=2)?"#99EE99":ville6 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1111.jpg>&nbsp;2 Mordred ('+mordred+')</TD>\
      </TR>\
       <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville7+';">'+unsafeWindow.g_js_strings.commonstr.city+' 7</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (Stag>=4)?"#99EE99":ville7 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1112.jpg>&nbsp;4 Roi Stag ('+Stag+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (Pendragon>=3)?"#99EE99":ville7 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1113.jpg>&nbsp;3 Terrestre ('+Pendragon+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (Lady>=2)?"#99EE99":ville7 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1114.jpg>&nbsp;2 Aquatique ('+Lady+')</TD>\
      </TR>\
      <TR CLASS="MYTABLE">  \
        <TD CLASS="MYTABLE" style="background-color:'+ville8+';">'+unsafeWindow.g_js_strings.commonstr.city+' 8</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (Merlin>=4)?"#99EE99":ville8 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1115.jpg>&nbsp;4 Merlin ('+Merlin+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (aetherseal>=3)?"#99EE99":ville8 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1120.jpg>&nbsp;3 Aetherseal ('+aetherseal+')</TD>\
        <TD CLASS="MYTABLE" style="background-color:'+( (ysbadden>=2)?"#99EE99":ville8 )+';"><img width=25 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1121.jpg>&nbsp;2 Ysbadden  ('+ysbadden +')</TD>\
      </TR>\
    </TBODY></TABLE><TABLE CLASS="MYTABLE" CELLPADDING=0 CELLSPACING=0><CAPTION CLASS="MYTABLE">Vos armoiries en stock</CAPTION><THEAD >\
        <TR CLASS="MYTABLE">\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1101.jpg title="Bor"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1102.jpg title="Ector"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1103.jpg title="Kay"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1104.jpg title="Bedivere"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1105.jpg title="Gawain"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1106.jpg title="Perceval"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1107.jpg title="Galaad"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1108.jpg title="Lancelot"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1109.jpg title="Arthur"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1110.jpg title="Morgane"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1111.jpg title="Mordred"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1112.jpg title="Stag"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1113.jpg title="Terrestre"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1114.jpg title="Aquatique"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1115.jpg title="Merlin"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1120.jpg title="Aetherseal"></TH>\
          <TH CLASS="MYTABLE"><img width=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1121.jpg title="Ysbadden"></TH>\
         </TR>\
 </THEAD><TR CLASS="MYTABLE">\
  <TD CLASS="MYTABLE"><center><b>'+bor+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+ector+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+kay+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+bedivere+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+gawain+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+percival+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+galahad+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+lancelot+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+arthur+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+morgana+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+mordred+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+Stag+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+Pendragon+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+Lady+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+Merlin+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+aetherseal+'</TD>\
  <TD CLASS="MYTABLE"><center><b>'+ysbadden+'</TD>\
  </TR><TR CLASS="MYTABLE"></tr>\
  </table>';
  
 t.cont.innerHTML = m;
        new CdispCityPicker ('ptloc1', ById('ptloc1'), true, t.eventFromLocChanged, 0).bindToXYboxes(ById('calcX'), ById('calcY'));
    new CdispCityPicker ('ptloc2', ById('ptloc2'), true, t.eventLocChanged, 0).bindToXYboxes(ById('calcX2'), ById('calcY2'));
     t.eventFromLocChanged(Cities.cities[0], Cities.cities[0].x, Cities.cities[0].y); 
    ById('idETASelect').addEventListener ( 'change', t.eventLocChanged, false); 
    function rlShow(rl) {
    			var retval = '<TD nowrap><B>'+rl.Name+'</B></TD><TD align=right><B>&nbsp;&nbsp;';
    			nlETA = ((rl.NextLevelETA > 0)?('(' + (rl.Level + 1) + ': ' + timestr(rl.NextLevelETA) + ')'):'');
    			retval += ((rl.Level < 9)?('<SPAN class=boldRed>' + rl.Level + '</SPAN></B></TD><TD nowrap>&nbsp;&nbsp;' + nlETA + '</TD>'):(rl.Level + '</B></TD><TD nowrap>&nbsp;&nbsp;' + nlETA + '</TD>'));
    			return retval;
    };
    var m = '';
    getResearchLevels();
    m += '<TABLE align=center cellpadding=1 cellspacing=0>' +
    			'<TR>' + rlShow(researchLevels[1]) + '<TD width=10></TD>' + rlShow(researchLevels[6]) + '<TD width=10></TD>' + rlShow(researchLevels[12]) + '</TR>' +
    			'<TR>' + rlShow(researchLevels[2]) + '<TD></TD>' + rlShow(researchLevels[8]) + '<TD></TD>' + rlShow(researchLevels[13]) + '</TR>' +
    			'<TR>' + rlShow(researchLevels[3]) + '<TD></TD>' + rlShow(researchLevels[9]) + '<TD></TD>' + rlShow(researchLevels[14]) + '</TR>' +
    			'<TR>' + rlShow(researchLevels[4]) + '<TD></TD>' + rlShow(researchLevels[15]) + '<TD></TD>' + rlShow(researchLevels[10]) + '</TR>' +
    			'<TR>' + rlShow(researchLevels[5]) + '<TD></TD>' + rlShow(researchLevels[11]) + '<TD></TD>' + rlShow(researchLevels[16]) + '</TR></TABLE>';
    ById('Research').innerHTML = m;
     for (var c=0; c<Cities.numCities; c++)      
        t.makeCityImg (c, ById('ptProvMap'));
      t.state = 1;
    }
  },
  makeCityImg : function (cityNum, eMap){
    var t = my.Info;
    var city = Cities.cities[cityNum];
    var x = parseInt((provMapCoords.mapWidth * city.x) / 750);
    var y = parseInt((provMapCoords.mapHeight * city.y) / 750);
    var ce = document.createElement ('div');
    ce.style.background = 'black';
    ce.style.opacity = '1.0';
    ce.style.position='relative';
    ce.style.display='block';
    ce.style.width='14px';
    ce.style.height='16px';
    ce.style.border='1px solid #fff';
    ce.style.color = 'white';
    ce.style.textAlign = 'center';
    ce.style.top = (y+provMapCoords.topMargin-(cityNum*16)-8) +'px';      
    ce.style.left = (x+provMapCoords.leftMargin-7) +'px';
    eMap.appendChild(ce);
    ce.innerHTML = (cityNum+1) +'';
  },
  
  eventLocChanged : function (city, x, y){
    var t = myBO.Info;
    var x1 = parseInt(ById('calcX').value);
    var x2 = parseInt(ById('calcX2').value);
    if (isNaN(x2))
      return;
    var y1 = parseInt(ById('calcY').value);
    var y2 = parseInt(ById('calcY2').value);
    var m = 'La Distance depuis '+ x1 +','+ y1 +' to '+ x2 +','+ y2 +' est : &nbsp;<B>'+ distance (x1, y1, x2, y2).toFixed(2) +'</b>';
    ById('ptdistout').innerHTML = m;
    var dist = distance (x1, y1, x2, y2);
    if (t.ModelCity) m = estETA(dist, ById('idETASelect').value, t.ModelCity.id,4)
     else 
      m = estETA(dist, ById('idETASelect').value, 0, 4)
    if (m != null)
           ById('ptETAout').innerHTML = "Attaque : "+m.etaStr+" - Renfort : "+m.friendEtaStr;
  },
  eventFromLocChanged : function (city, x, y){
    var t = myBO.Info;
    t.ModelCity = city;
    var x1 = parseInt(ById('calcX').value);
    var x2 = parseInt(ById('calcX2').value);
    if (isNaN(x2))
      return;
    var y1 = parseInt(ById('calcY').value);
    var y2 = parseInt(ById('calcY2').value);
    var m = 'La distance depuis '+ x1 +','+ y1 +' to '+ x2 +','+ y2 +' est : &nbsp;<B>'+ distance (x1, y1, x2, y2).toFixed(2) +'</b>';
    ById('ptdistout').innerHTML = m;
    var dist = distance (x1, y1, x2, y2);
       if (t.ModelCity) m = estETA(dist, ById('idETASelect').value, t.ModelCity.id,4)
        else 
      m = estETA(dist, ById('idETASelect').value, 0, 4)
    if (m != null)
       ById('ptETAout').innerHTML = "Attaque : "+m.etaStr+" - Renfort : "+m.friendEtaStr;
  },
}
myBO.Alliance = {
  tabOrder : 120,
  cont : null,
  alliancemembers:[],
  number:0,
  totalmembers:0,
  error:false,
  
  getContent : function (){
      var t = myBO.Alliance;
      return t.cont;
  },
  init : function (){
      var t = myBO.Alliance;
      t.cont = document.createElement('div');
      return t.cont;
  },  
  show : function (){    
     var t = myBO.Alliance;   
     t.cont.style.overflowY = 'scroll';
     t.cont.style.maxHeight = '500px';
     t.totalmembers=0;
     t.alliancemembers=[];	
     unsafeWindow.getdetails = t.getMemberDetails;
    var m =  '<DIV class=boStat><b>INFORMATIONS SUR L\'ALLIANCE</b></div><TABLE align=center cellpadding=1 cellspacing=0></table>';
    m +='<TABLE class=ptTab><TD width=200px>Liste des membres de l\'alliance</td><TD>Trier par : <select id="searchAlli"><option value="name">Nom</options>';
    m += '<option value="might">'+uW.g_js_strings.commonstr.might+'</option>';
    m += '<option value="login">'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+'</option>';
    m += '<option value="cities">'+uW.g_js_strings.commonstr.cities+'</option>';
    m += '<option value="position">Position</option>';
    m += '<option value="glory">Gloire</option><option value="dip">Jour dans cette position (dip)</option></select></td>';
    m += '<TD><INPUT id=alList type=submit value="Liste"></td>';
    m += '<TD id=progress></td>';
    m += '<TR><TD width=200px>Voir les diplomaties de l\'alliance</td><TD><INPUT id=aldiplo type=submit value="Liste des diplomaties"></td></tr></table>';
    m+='<DIV class=boStat><b>RESUME</div><TABLE align=center cellpadding=1 cellspacing=0 class=ptTab></table>';
    m += '<TABLE id=alOverviewTab class=alTab><TR align="center"></tr></table>';
   t.cont.innerHTML = m;
   ById('alList').addEventListener('click', function(){
    	if (!t.searching){
	    	t.totalmembers=0;
	    	t.alliancemembers=[];	
		    ById('alOverviewTab').innerHTML ="";
		    ById('progress').innerHTML ="";
		    ById('progress').innerHTML = "Recherche en cours...";
		    ById('alList').disabled = true;
		    t.error=false;
		    t.fetchAllianceMemberPage();
		} 
    }, false);
    
    ById('searchAlli').addEventListener('click', function(){
        if (t.alliancemembers!="") {
        	ById('alOverviewTab').innerHTML ="";
        	t.paintMembers(); 
        }
    }, false);
    ById('aldiplo').addEventListener('click', function(){t.paintDiplomacy();}, false);  
    
  window.addEventListener('unload', t.onUnload, false);
  },
  paintMembers: function(){
  var t = myBO.Alliance; 
	  		  if (ById('searchAlli').value == "name") {
				  var sortmembers = t.alliancemembers.sort(function(a, b){
				         var sortA=a.Name.toLowerCase(), sortB=b.Name.toLowerCase()
				         if (sortA < sortB) 
				          return -1
				         if (sortA > sortB)
				          return 1
				         return 0 
				        });
			  }     
			  if (ById('searchAlli').value == "might") {
			  	  var sortmembers = t.alliancemembers.sort(function(a, b){
			  	         var sortA=parseInt(a.Might),sortB=parseInt(b.Might)
			  	         if (sortA > sortB) 
			  	          return -1
			  	         if (sortA < sortB)
			  	          return 1
			  	         return 0 
			  	        });
			  }     
			  if (ById('searchAlli').value == "login") {
			  	  var sortmembers = t.alliancemembers.sort(function(a, b){
			  	         var sortA=a.LastLogin,sortB=b.LastLogin
			  	         if (sortA < sortB) 
			  	          return -1
			  	         if (sortA > sortB)
			  	          return 1
			  	         return 0 
			  	        });
			  }     
			  if (ById('searchAlli').value == "cities") {
			  	  var sortmembers = t.alliancemembers.sort(function(a, b){
			  	         var sortA=a.Cities,sortB=b.Cities
			  	         if (sortA < sortB) 
			  	          return -1
			  	         if (sortA > sortB)
			  	          return 1
			  	         return 0 
			  	        });
			  }     
			  if (ById('searchAlli').value == "dip") {
			  	  var sortmembers = t.alliancemembers.sort(function(a, b){
			  	         var sortA=a.dip,sortB=b.dip
			  	         if (sortA < sortB) 
			  	          return -1
			  	         if (sortA > sortB)
			  	          return 1
			  	         return 0 
			  	        });
			  }     
			  if (ById('searchAlli').value == "position") {
			  	  var sortmembers = t.alliancemembers.sort(function(a, b){
			  	         var sortA=a.Position,sortB=b.Position
			  	         if (sortA < sortB) 
			  	          return -1
			  	         if (sortA > sortB)
			  	          return 1
			  	         return 0 
			  	        });
			  } 
			  if (ById('searchAlli').value == "glory") {
			  	  var sortmembers = t.alliancemembers.sort(function(a, b){
			  	         var sortA=parseInt(a.glory),sortB=parseInt(b.glory);
			  	         if (sortA > sortB) 
			  	          return -1
			  	         if (sortA < sortB)
			  	          return 1
			  	         return 0 
			  	        });
			  }      
			  for (var y = (sortmembers.length-1); y >=0; y--) {
			                      t._addTab(sortmembers[y].Name,sortmembers[y].Might,sortmembers[y].LastLogin,sortmembers[y].Position,sortmembers[y].dip,sortmembers[y].uid,sortmembers[y].fbuid,sortmembers[y].Cities,sortmembers[y].avatarurl,sortmembers[y].glory,sortmembers[y].dateJoined);
			                      t.cont.style.overflowY = 'scroll';
			  }
			 t._addTabHeader();
   },
  
    _addTab: function(Name,Might,LastLogin,Position,dip,uid,fbuid,Cities,avatar,gloire,arrive){
             var t = myBO.Alliance;
             var row = ById('alOverviewTab').insertRow(0);
             row.vAlign = 'top';
             row.insertCell(0).innerHTML ='<img width=25 src="'+ avatar +'">';
             row.insertCell(1).innerHTML ='<A target="_tab" href="http://www.facebook.com/profile.php?id='+ fbuid +'">Profile</a>';
             row.insertCell(2).innerHTML = Name;
             var cell2 = row.insertCell(3);
       		 cell2.width = "60" ;
       		 cell2.align = "right" ;
       		 cell2.vAlign = "top";
       		 cell2.innerHTML = addCommas(Might);
       		var cell2 = row.insertCell(4);
       		 cell2.width = "60" ;
       		 cell2.align = "right" ;
       		 cell2.vAlign = "top"; 
       		 cell2.innerHTML = addCommas(gloire);
       		row.insertCell(5).innerHTML = Cities;
       		 row.insertCell(6).innerHTML = officerId2String (Position);
       		 row.insertCell(7).innerHTML = dip;
       		 row.insertCell(8).innerHTML = LastLogin;
       		 row.insertCell(9).innerHTML = arrive;
          }, 
          
    _addTabHeader: function() {
    var t = myBO.Alliance;
        var row = ById('alOverviewTab').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = "<b>Avatar";
        row.insertCell(1).innerHTML = "<b>Facebook";
        row.insertCell(2).innerHTML = "<b>Nom";
        row.insertCell(3).innerHTML = "<b>"+uW.g_js_strings.commonstr.might;
        row.insertCell(4).innerHTML = "<b>Gloire";
        row.insertCell(5).innerHTML = "<b>Villes";
        row.insertCell(6).innerHTML = "<b>Position";
        row.insertCell(7).innerHTML = "<b><span title='Jour dans cette position'>DIP</span>";
        row.insertCell(8).innerHTML = "<b>Der. Connexion";
        row.insertCell(9).innerHTML = "<b>Arriv&eacute;e";
    },   
    paintDiplomacy : function () {
    	ById('alOverviewTab').innerHTML ="";
    	ById('progress').innerHTML ="";
    	var m= '<TR><TD colspan=4 style=\'background: #33CC66;\' align=center><B>Amical : </b></td></tr>';
    	if (Seed.allianceDiplomacies['friendly'] == null) m+='<TR><TD>Aucune alliance...</td>';
    	else m += '<TABLE class=xtab><TR><TD>Nom de l\'Alliance</td><TD>Class&eacute; Membres</td></tr>';
    	for (k in Seed.allianceDiplomacies['friendly']){
				m+='<TR><TD>'+Seed.allianceDiplomacies['friendly'][k]['allianceName']+'</td>';
				m+='<TD align=center>'+Seed.allianceDiplomacies['friendly'][k]['membersCount']+'</td>';
    	}
    	m+='<TR></tr></table>';
    	m+= '<TR><TD colspan=4 style=\'background: #CC0033;\' align=center><B>Hostile : </b></td></tr>';
    	if (Seed.allianceDiplomacies['hostile'] == null) m+='<TR><TD>Aucune alliance...</td>';
    	else m += '<TABLE class=xtab><TR><TD>Nom de l\'Alliance</td><TD>Class&eacute; Membres</td></tr>';
    	for (k in Seed.allianceDiplomacies["hostile"]){
    		m+='<TR><TD>'+Seed.allianceDiplomacies["hostile"][k]['allianceName']+'</td>';
    		m+='<TD align=center>'+Seed.allianceDiplomacies["hostile"][k]['membersCount']+'</td>';
    	}
    	m+='<TR></tr></table>';
    	m+= '<TR><TD colspan=4 style=\'background: #FF6633;\' align=center><B>Amicalement pour vous : </b></td></tr>';
    	if (Seed.allianceDiplomacies['friendlyToYou'] == null) m+='<TR><TD>Aucunce alliance...</td>';
    	else m += '<TABLE class=xtab><TR><TD>Nom de l\'Alliance</td><TD>Class&eacute; Membres</td></tr>';
    	for (k in Seed.allianceDiplomacies["friendlyToYou"]){
    		m+='<TR><TD>'+Seed.allianceDiplomacies["friendlyToYou"][k]['allianceName']+'</td>';
    		m+='<TD align=center>'+Seed.allianceDiplomacies["friendlyToYou"][k]['membersCount']+'</td>';
    	}
    	m+='<TR></tr></table>';
    	ById('alOverviewTab').innerHTML = m;
    },
    
        
    fetchAllianceMemberPage : function () {
    var t = myBO.Alliance;
    ById('alList').disabled = true;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    
    params.pf = 0;
    
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetInfo.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (transport) {
      	  var rslt = eval("(" + transport.responseText + ")");
          t.totalmembers = (rslt["allianceInfo"]["members"]);
          for (var i=1;i<=10;i++) {
                 params.pageNo = i;
                 params.pf = 0;
                 new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetMembersInfo.php" + unsafeWindow.g_ajaxsuffix, {
                   method: "post",
                   parameters: params,
                   onSuccess: function (transport) {
                    var info = eval("(" + transport.responseText + ")");
                    if (info.ok) {  
                       for (var k in info["memberInfo"]){
                         if ( info["memberInfo"][k]["might"] != undefined && !t.error){  
                           t.alliancemembers.push ({
                               Name: info["memberInfo"][k]["name"],
                               Might: info["memberInfo"][k]["might"],
                               Cities: info["memberInfo"][k]["cities"],
                               Position : info["memberInfo"][k]["positionType"],
                               dip : info["memberInfo"][k]["daysInPosition"],
                               LastLogin : info["memberInfo"][k]["lastLogin"],
                               uid : info["memberInfo"][k]["userId"],
                               fbuid : info["memberInfo"][k]["fbuid"],	
                               avatarurl : info["memberInfo"][k]["avatarurl"],	
                               glory : info["memberInfo"][k]["glory"],	
                               dateJoined : info["memberInfo"][k]["dateJoined"],	
                           });
                          }
                           ById('alOverviewTab').innerHTML ="";
                           t.paintMembers();
                   		}
                       if (!t.error) ById('progress').innerHTML	 = '(' + (t.alliancemembers.length) +'/'+ t.totalmembers +')';
                       if ( t.alliancemembers.length >= t.totalmembers) ById('alList').disabled = false;
                    } else  if (info.error) {
                    	ById('alList').disabled = false;
                    	ById('progress').innerHTML = "ERREUR";
                    	t.error=true;
                   	}
                   },
                   onFailure: function (rslt) {;
                     notify ({errorMsg:'AJAX error'});
                   },
           });
          }
      },
      onFailure: function (rslt) {;
        notify ({errorMsg:'AJAX error'});
      },
    });
  },
  hide : function (){         
  },
};


/************************ Tournoi *************************/
myBO.Tournoi = {
 cont:null,
 state:0,
 
 displayTimer : null,
 init : function (){
    this.cont = document.createElement('div');
    return this.cont;
 },
 hide : function (){
  var t = myBO.Tournoi;
  clearTimeout (t.displayTimer);
 },
 getContent : function (){
	    var t = myBO.Tournoi;
	    return t.cont;
 },
 show : function () {
  var t = myBO.Tournoi;
  
  clearTimeout (t.displayTimer);
  
  t.cont.innerHTML = "<div class='tourny_modal_upsell'></div><DIV class=boStat><b>INFORMATIONS PRATIQUES POUR PREPARER UN TOURNOI - <input type=button value='?' id='boaidetournoi' class=boAide onclick=window.open('"+sitesupport+"?page=aide_tournoi');></b></div>";
  
 
  var mhtl = "<table width=100% class=ptTab><tr><td></td>";
  for(var i=0; i<Cities.numCities; i++) {
   mhtl += "<TD align=center valign=bottom width=60px><B>" + Cities.cities[i].name.replace(/ /g, "<BR>").substr(0,10) + "</B></TD>";
  }
  mhtl += "<td align=center><b>Total</td></tr><tr><td>Miliciens/h</td>";
  var temps=[],tot=0;
  for(var i=0; i<Cities.numCities; i++) {
   temps[i]=((Cities.cities[i]['Troop2Time'] > 0)?(3600 / Cities.cities[i]['Troop2Time']):0);
   mhtl += "<td align=right>" + addCommas(parseInt(temps[i])) +"</td>";
   tot+=parseInt(temps[i]);
  }
  mhtl += "<td align=right><b>"+addCommas(tot)+"</td></tr><tr><td>Population/h</td>";
  var pop=[],tot1=0;
  for(var i=0; i<Cities.numCities; i++) {
   cityID = 'city'+ Cities.cities[i].id;
   pop[i] =  parseInt(Seed.citystats[cityID]["pop"][1]) / 2;
   mhtl += "<td  align=right>" + addCommas(parseInt(pop[i])) +"</td>";
   tot1+=parseInt(pop[i]);
  }
  mhtl += "<td align=right><b>"+addCommas(tot1)+"</td></tr><tr><td>Diff&eacute;rence</td>";
  var diff=0;
  for(var i=0; i<Cities.numCities; i++) {
   diff = parseInt(pop[i] - temps[i]);
   var couleur=" style='color:green' ";
   if (diff<0) couleur=" style='color:red' ";
   mhtl += "<td "+couleur+"  align=right><b>" + addCommas(parseInt(diff)) +"</b></td>";
  }
  diff = parseInt(tot1 - tot);
  var couleur=" style='color:green' ";
  if (diff<0) couleur=" style='color:red' ";
  mhtl += "<td "+couleur+" align=right><b>" + addCommas(parseInt(diff)) +"</b></td></tr><tr><td></td></tr><tr><td>Bonheur</td>";
  for(var i=0; i<Cities.numCities; i++) {
   cityID = 'city'+ Cities.cities[i].id;
   var bon = parseInt(Seed.citystats[cityID]["pop"][2]); 
   var bonc = "red";
   if (bon>99) bonc="green";
   mhtl += "<td style='color:"+bonc+"'><center><b>"+bon+"</td>";
  }
  var now = unixTime();
  var totalpop=0;
  mhtl += "</tr><tr><td>Formation en cours</td>";
  var phtl = "</tr><tr><td>Pop dispo Form.</td>";
    for(var i=0; i<Cities.numCities; i++) {
     cityID = 'city'+ Cities.cities[i].id;
     var totTime = 0;
     var q = Seed.queue_unt[cityID]; 
     if (q!=null && q.length>0) {
         totTime = q[q.length-1][3] - now;
         totalpop=0;
         for (var zz=0; zz<q.length; zz++){
         totalpop += parseInt((parseInt(q[zz][1]) * unsafeWindow.unitcost['unt'+q[zz][0]][6]) / 2);
         }
     }
     if (totTime < 0) totTime = 0;
     if (totTime < 3600)
      var bonc="style='color:red'";
     else
      var bonc="";
     mhtl += "<td "+bonc+"><center><b>"+timestr(totTime)+"</td>";
     phtl += "<td "+bonc+"><center><b>"+addCommas(totalpop)+"</td>";
    }
  mhtl += '<tr><td></td></tr>'+phtl+'<tr><td><img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png></td>'
  for(var i=0; i<Cities.numCities; i++) {
   cityID = 'city'+ Cities.cities[i].id;
   var mine=Seed.resources[cityID]['rec4'][0] / 3600
   var bonc="";
   if (mine<=15000000) 
    var bonc="style='color:red'";
   
    mhtl += '<td "+bonc+" align=right><b>'+UniteKMG(parseInt(mine)) +'</td>';
  }
  mhtl += "</tr></table><br><DIV class=boStat><b>INFORMATIONS SUR LE TOURNOI EN COURS</b></div>";
  t.cont.innerHTML += mhtl;
  
  

  
  var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  params.format=2;
  params.tournyPos=0;
  
    	
  new AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/getLeaderboard.php"+unsafeWindow.g_ajaxsuffix, {  method:"post",  parameters:params,
  
  onSuccess:function(transport){
   var rslt=eval("("+transport.responseText+")");
   if(rslt.ok){
   
    if(!rslt.data){
	   
	t.cont.innerHTML +="<div class='tourny_modal_upsell'><br><center><b>"+unsafeWindow.g_js_strings.modal_tourny_changetab.notourny+"</b></center></div><br>";
	  
	  
    }else{ // fin rslt.data
     var tournyhtml=new Array();
     
     if(rslt.name){
	    tournyhtml.push("<div><center><b><u>"+rslt.name.replace('The Tournament of Might','Tournoi de puissance individuel !')+"</u></b></center></div>")
     }  else{
	    tournyhtml.push("<div class='tournymodaltitle'><center>"+unsafeWindow.g_js_strings.commonstr.tournament+"</div>")
     }
	   tournyhtml.push("<div>");
	   
	   
	   
	   if(rslt.startdate&&rslt.enddate){
	   	   	    var startTime=rslt.startdate;
	   	   	    var endTime=rslt.enddate;
	   	   	    var now=parseInt(new Date().getTime()/1000);
	   	   	    tournyhtml.push("<table width=100% align=center class=ptTab><tr bgcolor=#FE8888><td width=40%><b>D&eacute;but</td><td width=40%><b>Fin</td><td width=20%><b>Restant</td></tr>");
	   	   	    dt = new Date ();
	   	            dt.setTime (startTime * 1000);
	   	            dtf = new Date ();
	   	            dtf.setTime (endTime * 1000);
	   	           
	   	            var restant = endTime - now; 
	   	            
	   	   	   
	   	   	   tournyhtml.push("<tr><td>");
	   	   	     tournyhtml.push("" + dt.toLocaleDateString() + " - "+ dt.toLocaleTimeString());
	   	   	    tournyhtml.push("</td><td>");
	   	   	    tournyhtml.push("" + dtf.toLocaleDateString()+ " - "+ dtf.toLocaleTimeString());
	   	   	    tournyhtml.push("</td><td>"+timestr(restant,1)+"</td></tr></table>");
	   	     tournyhtml.push("<br>");
	   
	   }
	   
	   
	   tournyhtml.push("<center><table class='tourny_list_table' cellpadding='0' cellspacing='0' border='0' width=95% style='margin:5px'>");
	   tournyhtml.push("<thead>");
	   tournyhtml.push("<tr>");
     if(rslt.type==24){
	    tournyhtml.push("<td class='rankcol' style='background-color:red'>");
	    tournyhtml.push("<div><input type=button id='BOTournoiPM' value='-'>&nbsp;"+unsafeWindow.g_js_strings.commonstr.ranking+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td  style='background-color:red'>");
	    tournyhtml.push("<div>"+unsafeWindow.g_js_strings.modal_tourny_changetab.chancellorname+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td  style='background-color:red'>");
	    tournyhtml.push("<div>"+unsafeWindow.g_js_strings.commonstr.alliance+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td  style='background-color:red'>");
	    tournyhtml.push("<div>"+unsafeWindow.g_js_strings.modal_tourny_changetab.mightgained+"</div>");
	    tournyhtml.push("</td  style='background-color:red'>");
	    tournyhtml.push("<td  style='background-color:red'> ");
	    tournyhtml.push("<div>"+unsafeWindow.g_js_strings.modal_tourny_changetab.rewardperplayer+"</div>");
	    tournyhtml.push("</td>")
      }else{
            tournyhtml.push("<td	class='rankcol' style='background-color:red'>");
	    tournyhtml.push("<div><input type=button id='BOTournoiPM' value='-'>&nbsp;"+unsafeWindow.g_js_strings.commonstr.ranking+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td  style='background-color:red'>");
	    tournyhtml.push("<div>Nom Joueur</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td  style='background-color:red'>");
	    tournyhtml.push("<div>"+unsafeWindow.g_js_strings.commonstr.alliance+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td  style='background-color:red'>");
	    tournyhtml.push("<div>"+rslt.contestcategory+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td  style='background-color:red'>");
	    tournyhtml.push("<div>"+unsafeWindow.g_js_strings.commonstr.reward+"</div>");
	    tournyhtml.push("</td>")
     }
	   tournyhtml.push("</tr>");
	   tournyhtml.push("</thead>");
	   tournyhtml.push("</tbody>");
	   var nb=rslt.data.length;
	   var votrepuissance = 0;
	   for(var i=0;i<rslt.data.length;i++){
	    var row=rslt.data[i];
	    if(rslt.type==24){
	     // pour le tournoi alliance
	     if (getMyAlliance()[1] == row.alliance) {
	      votrepuissance=row.contestValue;
	      break;
	     }
	    } else {
	     if (Seed.player.prefix + ' '+ Seed.player.name == row.name ) {
	      votrepuissance=row.contestValue;
	      break;
	     }	
	    }
	   }
	   for(var i=0;i< Options.TournoiLigne;i++){
	    var row=rslt.data[i];
	    var rewardString=row.itemCount+" ";
	    if(row.itemType==0){
	     rewardString+=unsafeWindow.g_js_strings.commonstr.gems;
	    }else{
	     rewardString+=unsafeWindow.itemlist["i"+row.itemType].name;
	    }
	    var couleur="";
	    if(rslt.type==24){
	     // pour le tournoi alliance
	     if (getMyAlliance()[1] == row.alliance) {
	      couleur=" style='background-color:#77FF77' ";
	     }
	    }else{
	     if (getMyAlliance()[1] == row.alliance) {
	       if(i%2==1){
	     	      couleur=" style='background-color:#FF9977' ";
	     	    }else{
	     	      couleur=" style='background-color:#FFAA88' ";
	       }
	     
	     }
	     if (Seed.player.prefix + ' '+ Seed.player.name == row.name ) {
	      couleur=" style='background-color:#77FF77' ";
	     }
	    }
	    if(i%2==1){
	     tournyhtml.push("<tr>")
	    }else{
	     tournyhtml.push("<tr class='stripe'>")
	    }
	    tournyhtml.push("<td class='rankcol' "+couleur+">");
	    tournyhtml.push("<div><b>"+row.ranking+"</b></div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td "+couleur+">");
	    tournyhtml.push("<div>"+row.name+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td "+couleur+">");
	    tournyhtml.push("<div>"+(row.alliance||"----")+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td "+couleur+">");
	    tournyhtml.push("<div>"+addCommas(row.contestValue));
	    if (votrepuissance>0) {
	      var ecartavecvous = parseInt(row.contestValue - votrepuissance);
	      if (ecartavecvous>0) {
	       tournyhtml.push("&nbsp;(+ " + addCommas(ecartavecvous) +")");
	      } 
	      if (ecartavecvous<0) {
	       tournyhtml.push("&nbsp;(" + addCommas(ecartavecvous) +")");
	      }
	    }
	    tournyhtml.push("</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("<td "+couleur+">");
	    tournyhtml.push("<div>"+rewardString+"</div>");
	    tournyhtml.push("</td>");
	    tournyhtml.push("</tr>")
	   } // fin du for
	
	      if(rslt.type!=24){

	    for(var i= Options.TournoiLigne;i<rslt.data.length;i++){
	   	    var row=rslt.data[i];
	   	 
	   	    if (Seed.player.prefix + ' '+ Seed.player.name == row.name ) {
	   	      var rewardString=row.itemCount+" ";
	   	     	    if(row.itemType==0){
	   	     	     rewardString+=unsafeWindow.g_js_strings.commonstr.gems;
	   	     	    }else{
	   	     	     rewardString+=unsafeWindow.itemlist["i"+row.itemType].name;
	   	     	    }
	   	     	    tournyhtml.push("<tr class='stripe' >")
	   	     	    tournyhtml.push("<td class='rankcol' style='background-color:#77FF77'>");
	   	     	    tournyhtml.push("<div><b>"+row.ranking+"</b></div>");
	   	     	    tournyhtml.push("</td>");
	   	     	    tournyhtml.push("<td style='background-color:#77FF77'>");
	   	     	    tournyhtml.push("<div>"+row.name+"</div>");
	   	     	    tournyhtml.push("</td>");
	   	     	    tournyhtml.push("<td style='background-color:#77FF77'>");
	   	     	    tournyhtml.push("<div>"+(row.alliance||"----")+"</div>");
	   	     	    tournyhtml.push("</td>");
	   	     	    tournyhtml.push("<td style='background-color:#77FF77'>");
	   	     	    tournyhtml.push("<div>"+addCommas(row.contestValue)+"</div>");
	   	     	    tournyhtml.push("</td>");
	   	     	    tournyhtml.push("<td style='background-color:#77FF77'>");
	   	     	    tournyhtml	.push("<div>"+rewardString+"</div>");
	   	     	    tournyhtml.push("</td>");
	   	            tournyhtml.push("</tr>")
	   	   }    
	   }
	   }
	   tournyhtml.push("</tbody>");
	   tournyhtml.push("</table>");
      tournyhtml.push("</div>");
      t.cont.innerHTML += tournyhtml.join("");      
           ById('BOTournoiPM').addEventListener ('click', 
           function() { 
            var lg=rslt.data.length;
            if (rslt.type!=24) lg=25;
            t.plusmoins(lg);
           }, false);      
           
           if ((Options.TournoiLigne==5 && rslt.type!=24) || (Options.TournoiLigne==5 && rslt.type==24)) {
	        ById('BOTournoiPM').value="+";
	    } else {
	        ById('BOTournoiPM').value="-";       
        }
          } // fin rslt.data 
         } else {
            t.cont.innerHTML = "<div class='tourny_modal_upsell'><center>Erreur de chargement</div>";
         }
       }, onFailure:function()  {
         t.cont.innerHTML = "<div class='tourny_modal_upsell'><center>Erreur de chargement</div>";
       }
   });
   t.displayTimer = setTimeout (t.show, 240000);       
  },
  plusmoins: function(lg) {
   var t = myBO.Tournoi;
   if (ById('BOTournoiPM').value=="+") {
     ById('BOTournoiPM').value="-";
     Options.TournoiLigne = lg;
   } else {
     ById('BOTournoiPM').value="+";
     Options.TournoiLigne = 5;
   }
   saveOptions();
   clearTimeout (t.displayTimer);
   t.show();
  },  
},


/************************ Ressources **********************/
myBO.Resources = {
   cont:null,
  resource : {1:unsafeWindow.g_js_strings.commonstr.food, 2:'Bois', 3:'Pierre', 4:'Minerais'},
  users : [],
  doList : [], // list of gifts to accept
  accepting : false,
  city : null,
  total : {gold:0, 1:0, 2:0, 3:0, 4:0},
  
  init : function (){
    this.cont = document.createElement('div');
    return this.cont;
  }, 
  show : function (){
    var t = myBO.Resources;
    this.cont.style.overflowY = 'scroll';
     this.cont.innerHTML = '<DIV class=boStat><b>VISITER LES COURS AUTOMATIQUEMENT</b></div><TABLE cellpadding=0 cellspacing=0 class=pbTab width=100%><TR><TD align=center><INPUT id="pballlist" type=submit value="Membres de l\'alliance" \><INPUT id="pballlist2" type=submit value="Mes amis" \></td></tr></table><HR>\
        <DIV id=resDiv style="width:100%; min-height:300px; height:100%">';
    ById('pballlist').addEventListener ('click', function() { t.e_clickfetchlist(1); }, false);
    ById('pballlist2').addEventListener ('click', function() { t.e_clickfetchlist(2); }, false);
  },
  
  hide : function (){
  },
  
  progress : function (msg, span, add){
	if(add)
		ById(span).innerHTML+=msg;
	else
		ById(span).innerHTML=msg;
  },

  e_clickfetchlist : function  (tt){     // (also cancel accepting)
    var t = myBO.Resources;
	t.users = [];
    if (t.accepting){
      ById('pballlist').value = 'Membres de l\'alliance';
      ById('resDiv').innerHTML+= '<BR><SPAN class=boldRed>Annul&eacute;.</span>';
      t.accepting = false;
      return;
    }
    if (tt==1) ById('resDiv').innerHTML = 'R&eacute;cup&eacute;ration en cours de la liste des membres... <span id=pbResUserListCount></span>';
    if (tt==2) ById('resDiv').innerHTML = 'R&eacute;cup&eacute;ration en cours de la liste des amis.. <span id=pbResUserListCount></span>';
    
    t.fetchUserList (tt, gotUserList);
    function gotUserList(userList){
		if(userList.length < 1){
			listGifts();
			return;
		}
		ById('resDiv').innerHTML += '<BR>V&eacute;rification s\'il est possible de collecter ... <span id=pbResUserAvailCount></span>';
		t.checkDailyAction(userList, listGifts);
	}
    
    function listGifts (){
	  t.city = Cities.cities[0];
	  var m = '<DIV class=boStat><CENTER>LISTES DES MEMBERS &nbsp; &nbsp; &nbsp; ('+ t.users.length +' trouv&eacute;)</center></div>';
      if (t.users.length<1){
        ById('resDiv').innerHTML = m + '<BR><BR><CENTER>Aucun membre de trouv&eacute;!</center>';
        return;
      }
      m += '<TABLE class=pbTab align=center><TR><TD align=right>'+unsafeWindow.g_js_strings.commonstr.city+' : </td><TD id=pbrescityselspan></td></tr>\
          <TR><TD align=right>Ressource &agrave; collecter : </td><TD>'
        + htmlSelector (t.resource, Options.getResType, 'id=pbResColType')
        + '</td></tr><TR><TD>S&eacute;lectionner les membres: </td><TD width=250><INPUT type=submit id=pbResDo value="Accepter les Ressources">\
        &nbsp; <SPAN id=pbResNone class=boldRed></span></td></tr></table><HR><TABLE class=pbTab><TR valign=top><TD>\
        <INPUT id=pbResButAll type=submit value="Tout" style="width:100%; margin-bottom:5px"><BR><INPUT id=pbResButNone type=submit value="Aucun"></td>\
        <TD width=10></td><TD><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabLined>\
        <TBODY id=pbResTbody style="height:250px; overflow:auto; display:block;">\
        <TR style="font-weight:bold; background:white"><TD>Nom</td><TD>'+uW.g_js_strings.commonstr.might+'</td><TD width=20></td></tr>';
      for (var i=0; i<t.users.length; i++){
        m += '<TR><TD><INPUT type=checkbox id=pbrchk_'+ i +'> &nbsp;'+ t.users[i].name +'</td><TD>'+ t.users[i].might +'</td></tr>';
      }
      ById('resDiv').innerHTML = m + '</tbody></table></td></tr></table>';
	  new CdispCityPicker ('pbrescitysel', ById('pbrescityselspan'), true, t.e_CityButton, t.city.idx);
      ById('pbResDo').addEventListener ('click', t.getErDone, false);
      ById('pbResButAll').addEventListener ('click', t.e_butAll, false);
      ById('pbResButNone').addEventListener ('click', t.e_butNone, false);
      // var tbody = ById('pbResTbody');
      // tbodyScroller (tbody, getRemainingHeight (tbody, mainPop.div));
    }
  },

  e_CityButton : function (city, x, y){
    var t = myBO.Resources;
	t.city = city;
  },
  
  e_butAll : function (){
    var t = myBO.Resources;
    for (var i=0; i<t.users.length; i++)
      ById('pbrchk_'+i).checked = true;
  },
  
  e_butNone : function (){
    var t = myBO.Resources;
    for (var i=0; i<t.users.length; i++)
      ById('pbrchk_'+i).checked = false;
  },
  
  getErDone : function (){
    var t = myBO.Resources;
    t.doList = [];
    ById('pbResNone').innerHTML = '';
	Options.getResType = ById('pbResColType').value;
	t.total = {gold:0, 1:0, 2:0, 3:0, 4:0};
    for (var i=0; i<t.users.length; i++){
      if (ById('pbrchk_'+i).checked)
        t.doList.push (t.users[i]);
    }
    if (t.doList.length==0){
      ById('pbResNone').innerHTML = 'Rien de s&eacute;lectionn&eacute; !';
      return;
    }
    t.accepting = true;
    ById('pballlist').value = 'Stopper l\'acceptation';
    ById('resDiv').innerHTML = '<DIV id=rsltDiv style="height:400px; max-height:400px; overflow-y:auto"><B>Collecte en cours sur '+ t.doList.length +' membres :</b><BR></div>';    
    t.acceptNext ();
  },

    
  allDone : function (msg){
    var t = myBO.Resources;
	msg += '<BR><BR> Total ressources obtenues : <BR>\
		   Or : '+addCommas(t.total.gold)+'<BR>';
	for(var i=1; i<=4; i++){
		msg += t.resource[i]+': '+addCommas(t.total[i])+'<BR>';
	}
    ById('rsltDiv').innerHTML += '<BR><BR>' + msg;
    ById('pballlist').value = 'Membres de l\'alliance';
    t.accepting = false;
  },
  
    
  acceptNext : function (){
    var t = myBO.Resources;
    var gift = t.doList.shift();
    if (gift == null){
      t.allDone ('Acceptation des ressources termin&eacute;e.');
      return;
    }
    var acpDiv = ById('rsltDiv');
    var curDiv = document.createElement ('div');
    acpDiv.appendChild (curDiv);
    curDiv.innerHTML = '<B>De '+ gift.name +': ';    
    var statSpan = document.createElement ('span');
    curDiv.appendChild (statSpan);
    statSpan.innerHTML = 'Acceptation en cours... ';
    t.getCourtAction (gift, gotGiftData);
        
    function gotGiftData (rslt){
      if (!t.accepting)
        return;
      if (rslt.ok){
        var msg = rslt.gold +' or et '+rslt.resource +' '+ t.resource[rslt.resourcetype]+'&nbsp; &nbsp; <b>OK</b>.';
        statSpan.innerHTML += msg;
		t.total.gold += rslt.gold;
		t.total[rslt.resourcetype] += rslt.resource;
		t.acceptNext ();  
        return;
      }
        
      if (rslt.msg)
        msg = '<B>'+ rslt.msg + '</b>';
      else
        msg = '<SPAN class=boldRed>ERREUR : '+ rslt.ajaxErr +'</span>';

      curDiv.removeChild (statSpan);
      curDiv = document.createElement ('div');
      curDiv.className = 'indent25';
      acpDiv.appendChild (curDiv);
      curDiv.innerHTML = msg;
      t.acceptNext ();  
    }
    
  },

  getMembersInfo : function (pageNo, notify) {
    var t = myBO.Resources;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    
    params.pageNo = pageNo;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetMembersInfo.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify ({errMsg:'Ajax Comm Error'});
      },
    });
  },
    getFriendsInfo : function (notify) {
      var t = myBO.Resources;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getAppFriends.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (rslt) {
          notify (rslt);
        },
        onFailure: function (rslt) {
          notify ({errMsg:'Ajax Comm Error'});
        },
      });
  },
  getDailyAction : function (uid, notify){
	var t = myBO.Resources;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    
    params.pid = uid;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify ({errMsg:'Ajax Comm Error'});
      },
    });
  },
  
  getCourtAction : function (gift, notify){
	var t = myBO.Resources;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    
    params.atype = Options.getResType;
	params.toid = gift.userId;
	params.givercityid = t.city.id;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/courtDoAction.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify ({errMsg:'Ajax Comm Error'});
      },
    });
  },
  
  checkDailyAction : function (userList, notify){
	var t = myBO.Resources;
	var count = 0;
    t.getDailyAction(userList[count].userId, parseViewCourt);
	
	function parseViewCourt (rslt){
		if (!rslt.ok || rslt.errMsg)
			notify ({errMsg:'Ajax Comm Error'});
		if(rslt.dailyActionFlag == 0)
			t.users.push(userList[count]);
		t.progress(count, 'pbResUserAvailCount');
		count++;
		if(count < userList.length){
			t.getDailyAction(userList[count].userId, parseViewCourt);
		} else {
			notify();
		}
	}
  },
  fetchUserList : function (tt, notify){
    var t = myBO.Resources;
    var userList = [];
    if (tt==1)
      t.getMembersInfo(1, parseAlliancePage);
    
    if (tt==2)
      t.getFriendsInfo(parseAlliancePage2);
    function parseAlliancePage (rslt){
      if (!rslt.ok || rslt.errMsg)
        notify ({errMsg:'Ajax Comm Error'});
	  var users = rslt.memberInfo;
      for(var k in users){
		userList.push({userId:users[k].userId, name:users[k].name, might:users[k].prestige, type:'alliance'});
	  }
	  t.progress(userList.length, 'pbResUserListCount');
	  if(rslt.currentPage < rslt.noOfPages){
		t.getMembersInfo((rslt.currentPage+1), parseAlliancePage);
	  } else {
		notify(userList);
		//t.getFriendsInfo(parseAlliancePage2);
	  }
    }
    
    
    function parseAlliancePage2 (rslt){
	      if (!rslt.ok || rslt.errMsg)
	        notify ({errMsg:'Ajax Comm Error'});
		  var users = rslt.data;
	          for(var k in users){
	             if (users[k].userId!=undefined)
			userList.push({userId:users[k].userId, name:users[k].displayName, might:users[k].might, type:'friends'});
		  }
		  t.progress(userList.length, 'pbResUserListCount');
		  notify(userList);
    }
	
  },
   getContent : function (){
  	    var t = myBO.Resources;
  	    return t.cont;
 },
},



/******************* Combat Tab **********************/
myBO.Combat = {
	cont: null,
	troops: [{},{}], //Array[Defender, Attacker]
	active: [{},{}],
	lost: [{},{}],
	total: [],
	stats: unsafeWindow.unitstats,   //  Life, Attack, Defense, Speed, Range, Load
	priority: [[3,7,8,4,5,6,2,1,9,11,10,12],[12,10,6,3,7,8,4,5,2,1,9,11]],
	round: 0,
	range: [0,0,0], //[Defender, Attacker, Max]
	distance: [{},{}], // [Defender, Attacker]
	speed: [0,0], // [Defender max, Attacker max]
	start: 0,
	pop:null,
	getContent : function (){
	    var t = myBO.Combat;
   	    return t.cont;
   	    },
	init: function(div){
		var t = myBO.Combat;
		t.cont = document.createElement('div');
     	        return t.cont;
     	    },
     	show: function() {
		var t = myBO.Combat;
		var m = '<div class=boStat>SIMULATION DE COMBAT (ATTAQUE / DEFENSE)</div><br>Attention : Ce comparateur ne prend pas en compteur tout les &eacute;lements pour faire une simulation &agrave; 100% fiable.<br><table><TR><TD colspan=2><b>'+uW.g_js_strings.commonstr.attacker+'&nbsp;&nbsp;<INPUT id=pbcombat_1 type=submit value="'+uW.g_js_strings.commonstr.research+'"></b></td><TD colspan=2><b>D&eacute;fenseur&nbsp;&nbsp;<INPUT id=pbcombat_0 type=submit value="Recherche"></b></td></TR>';
		for(var troops in unsafeWindow.unitcost){
			var name = unsafeWindow.unitcost[troops][0];
			m+='<tr><td>'+name+' :</td><td><input type=text id="pbcombata_'+troops+'" /></td><td>'+name+' :</td><td><input type=text id="pbcombatd_'+troops+'" /></td></tr>';
		}
		m+='</table><DIV id=pbcombat_rslt></div>';
		t.cont.innerHTML = m;
		
		for(var troops in unsafeWindow.unitcost){
			ById('pbcombata_'+troops).addEventListener('change', t.e_calculate, false);
			ById('pbcombatd_'+troops).addEventListener('change', t.e_calculate, false);
		}
		document.getElementById('pbcombat_0').addEventListener('click', function() t.e_research(0),false);
		document.getElementById('pbcombat_1').addEventListener('click', function() t.e_research(1),false);
	},
	e_research : function(side){
			var t = myBO.Combat;
			t.pop = new CPopup ('pbcombatresearch', 0, 0, 270, 300, true, function(){t.c_ratio(); t.pop.destroy();});
			t.pop.centerMe (mainPop2.getMainDiv()); 
			t.pop.getTopDiv().innerHTML = '<CENTER><B>Niveaux de technologies et autres</b>: '+ (side?'Attacker':'Defender') +'</center>';
			var m = '<DIV><TABLE>';
			for(var k in CombatOptions.research[side]){
				m += '<TR><TD>'+unsafeWindow.techcost[k][0]+':</td><td><input id="pbcombat_'+k+'" /></td></tr>';
			}
			m += '<TR><TD>Chevalier :</td><td><input id="pbcombat_knt" value='+ CombatOptions.knt[side] +' /></td></tr>';
			m += '<TR><TD>Guardien : </td><td> \
				  <table><tr><td>Type: </td><td>'+ htmlSelector({wood:'Bois',ore:'Minerais'},CombatOptions.guardian[side][0],'id=pbcombat_guartype') +'</td></tr><tr>\
				  <td>Niveau : </td><td><input id="pbcombat_guarlvl" value='+ CombatOptions.guardian[side][1] +' size=4 /></td></tr></table>\
				  </td></tr>';
			m += '<TR><TD colspan=2><CENter>';
			if (side==1) {
			 m+='<button id=pbcombatmyresearch>Mes Technologies</button>'
			}
			m+='<button id=pbcombatresearchsave>Enregistrer</button></CENTER></td></tr></table></div>';
			t.pop.getMainDiv().innerHTML = m;
			t.pop.centerMe (mainPop2.getMainDiv());  
			t.pop.show (true);
			for(var k in CombatOptions.research[side]){
				t.e_saveresearch('pbcombat_'+k, k, side);
			}
			document.getElementById('pbcombat_knt').addEventListener('change',function(){
				CombatOptions.knt[side] = parseInt(document.getElementById('pbcombat_knt').value);
				saveCombatOptions();
			},false);
			document.getElementById('pbcombat_guartype').addEventListener('change',function(){
				CombatOptions.guardian[side][0] = document.getElementById('pbcombat_guartype').value;
				saveCombatOptions();
			},false);
			document.getElementById('pbcombat_guarlvl').addEventListener('change',function(){
				CombatOptions.guardian[side][1] = parseInt(document.getElementById('pbcombat_guarlvl').value);
				saveCombatOptions();
			},false);
			ById('pbcombatresearchsave').addEventListener('click',t.c_ratio,false);
			
			ById('pbcombatresearchsave').addEventListener('click',t.c_ratio,false);
			if (side==1) {

			 ById('pbcombatmyresearch').addEventListener('click', function () {
			 
			     	getResearchLevels ();
			        CombatOptions.research[1]['tch8']=researchLevels[8].Level;
			     	CombatOptions.research[1]['tch9']=researchLevels[9].Level;
			     	CombatOptions.research[1]['tch13']=researchLevels[13].Level;
    		  		CombatOptions.research[1]['tch15']=researchLevels[15].Level;

    		  		var marshallCombatScore = 0;
    		  		if (parseIntNan(Options.alertConfig.hq)>0) {
				 var s = Seed.knights['city'+Options.alertConfig.hq];
				 if (s) {
				  s = s["knt" + Seed.leaders['city'+Options.alertConfig.hq].combatKnightId];
				  if (s){
					marshallCombatScore = s.combat;
				  }
				 }
				}
    		  		CombatOptions.knt[1] = marshallCombatScore;
   		  		
    		  				for(var i=0; i < Cities.numCities; i++){
							if(Seed.guardian[i].cityId == Options.alertConfig.hq){
								CombatOptions.guardian[1][1]= Seed.guardian[i].level;
								CombatOptions.guardian[1][0]= Seed.guardian[i].type;
							}
				}		
    		  		
    		  		saveCombatOptions();
				t.e_research(1);
			 
			 },false);
			 
			
			}
		},
		
		e_saveresearch : function(checkboxId, optionName, side){
			var t = myBO.Combat;
			var checkbox = document.getElementById(checkboxId);
			if (CombatOptions.research[side][optionName])
			  checkbox.value = CombatOptions.research[side][optionName];
			checkbox.addEventListener ('change', new eventToggle(checkboxId, optionName, side).handler, false);
			function eventToggle (checkboxId, optionName, side){
			  this.handler = handler;
			  var optName = optionName;
			  function handler(event){
				CombatOptions.research[side][optionName] = parseInt(this.value);
				saveCombatOptions();
			  }
			}
		},
		
		c_ratio : function (){
			var t = myBO.Combat;
			for(var k in CombatOptions.ratio[0]){
				var attack = parseFloat(t.c_attack(k,0));
				for(var tr in unsafeWindow.unitcost){
					var defense = parseFloat(t.c_defense(tr,1));
					var life = parseFloat(t.c_life(tr,1));
					var ratio = ((life+defense)/attack);
					CombatOptions.ratio[0][k][tr] = ratio.toFixed(20);
				}
			}
			for(var k in CombatOptions.ratio[1]){
				var attack = parseFloat(t.c_attack(k,1));
				for(var tr in unsafeWindow.unitcost){
					var defense = parseFloat(t.c_defense(tr,0));
					var life = parseFloat(t.c_life(tr,0));
					var ratio = ((life+defense)/attack);
					CombatOptions.ratio[1][k][tr] = ratio.toFixed(20);
				}
			}
	},
	e_calculate: function(){
		var t = myBO.Combat;
		t.round = 0;
		t.total[0] = 0;
		t.total[1] = 0;
		t.range[0] = 0
		t.range[1] = 0;
		t.speed[0] = 0;
		t.speed[1] = 0;
		for(var tr in unsafeWindow.unitcost){
			var name = unsafeWindow.unitcost[tr][0];
			t.troops[0][tr] = parseIntNan(ById('pbcombatd_'+tr).value);
			t.troops[1][tr] = parseIntNan(ById('pbcombata_'+tr).value);
			t.total[0] += t.troops[0][tr];
			t.total[1] += t.troops[1][tr];
			t.lost[0][tr] = 0;
			t.lost[1][tr] = 0;
			t.active[0][tr] = 0;
			t.active[1][tr] = 0;
			if(t.troops[0][tr]>0 && parseInt(t.stats[tr][4]) > t.range[0]) t.range[0] = parseInt(t.stats[tr][4]);
			if(t.troops[1][tr]>0 && parseInt(t.stats[tr][4]) > t.range[1]) t.range[1] = parseInt(t.stats[tr][4]);
			if(t.troops[0][tr]>0 && parseInt(t.stats[tr][3]) > t.speed[0]) t.speed[0] = parseInt(t.stats[tr][3]);
			if(t.troops[1][tr]>0 && parseInt(t.stats[tr][3]) > t.speed[1]) t.speed[1] = parseInt(t.stats[tr][3]);
		}
		if(t.range[1]>t.range[0]){
			t.start = 1; //Attacker starts first if range is longer than defender
			t.range[2] = t.range[1];
		} else {
			t.start = 0;
			t.range[2] = t.range[0];
		}
		for(var tr in unsafeWindow.unitcost){
			if(t.troops[0][tr]>0)
				t.distance[0][tr] = parseInt(t.range[2]/((t.speed[1]/t.speed[0])+1));
			else
				t.distance[0][tr] = 0;
			if(t.troops[1][tr]>0)
				t.distance[1][tr] = parseInt(t.range[2]/((t.speed[0]/t.speed[1])+1));
			else
				t.distance[1][tr] = 0;
		}
		t.c_rounds();
	},
	
	c_rounds: function(){
		var t = myBO.Combat;
		if(t.total[0]<1 || t.total[1]<1 || t.round>99){

			t.print();
			return;
		}
		t.round++;
		if(t.round>1){
			for(var tr in t.distance[0]){
				t.distance[0][tr] -= t.stats[tr][3];
				if(t.distance[0][tr] < 1) t.distance[0][tr] = 0;
			}
			for(var tr in t.distance[1]){
				t.distance[1][tr] -= t.stats[tr][3];
				if(t.distance[1][tr] < 1) t.distance[1][tr] = 0;
			}
		}
		t.c_remainder();
	},
	
		c_remainder: function(){  //  Life, Attack, Defense, Speed, Range, Load
			var t = myBO.Combat;
			for(var tr in t.troops[0]){ //Only troops in range are counted
				if(t.stats[tr][4] >= (t.distance[0][tr]))
					t.active[0][tr] = t.troops[0][tr];
			}
			for(var tr in t.troops[1]){
				if(t.stats[tr][4] >= (t.distance[1][tr]))
					t.active[1][tr] = t.troops[1][tr];
			}
			//Defender
			for(var tr in t.active[0]){
				if(t.active[0][tr] < 1) continue;
				var range = t.stats[tr][4] - t.distance[0][tr];
				var count = 0;
				var type = 0;
				if(tr == 'unt6' || tr == 'unt10' || tr == 'unt12') type = 1;
				// GM_log('side0 '+type);
				while(t.active[0][tr] > 0 && count<t.priority[type].length){
					var trr = 'unt'+t.priority[type][count];
					if((t.troops[1][trr] < 1) || (range < t.distance[1][trr])){
						count++;
						continue;
					}
					if(parseInt(CombatOptions.ratio[0][tr][trr]) < 1){
						if(t.active[0][tr] > t.troops[1][trr]){
							t.active[0][tr] -= t.troops[1][trr];
							t.lost[1][trr] += t.troops[1][trr];
							t.total[1] -= t.troops[1][trr];
							t.troops[1][trr] = 0;
						}else {
							t.lost[1][trr] += t.active[0][tr];
							t.total[1] -= t.active[0][tr];
							t.troops[1][trr] -= t.active[0][tr];
							t.active[0][tr] = 0;
						}
					} else {
						var killed = parseInt(t.active[0][tr]/CombatOptions.ratio[0][tr][trr]);
						if(killed > t.troops[1][trr]){
							t.lost[1][trr] += t.troops[1][trr];
							t.total[1] -= t.troops[1][trr];
							t.active[0][tr] -= parseInt(CombatOptions.ratio[0][tr][trr]* t.troops[1][trr]);
							t.troops[1][trr] = 0;
						} else {
							t.lost[1][trr] += killed;
							t.total[1] -= killed;
							t.troops[1][trr] -= killed;
							t.active[0][tr] = 0;
						}
					}
					count++;
				}
			}
			
			//Attacker
			for(var tr in t.active[1]){
				if(t.active[1][tr] < 1) continue;
				var range = t.stats[tr][4] - t.distance[1][tr];
				var count = 0;
				var type = 0;
				if(tr == 'unt6' || tr == 'unt10' || tr == 'unt12') type = 1;
				// GM_log('side1 '+type);
				while(t.active[1][tr] > 0 && count<t.priority[type].length){
					var trr = 'unt'+t.priority[type][count];
					if((t.troops[0][trr] < 1) || (range < t.distance[0][trr])){
						count++;
						continue;
					}
					if(parseInt(CombatOptions.ratio[1][tr][trr]) < 1){
						if(t.active[1][tr] > t.troops[0][trr]){
							t.active[1][tr] -= t.troops[0][trr];
							t.lost[0][trr] += t.troops[0][trr];
							t.total[0] -= t.troops[0][trr];
							t.troops[0][trr] = 0;
						}else {
							t.lost[0][trr] += t.active[1][tr];
							t.total[0] -= t.active[1][tr];
							t.troops[0][trr] -= t.active[1][tr];
							t.active[1][tr] = 0;
						}
					} else {
						var killed = parseInt(t.active[1][tr]/CombatOptions.ratio[1][tr][trr]);
						if(killed > t.troops[0][trr]){
							t.lost[0][trr] += t.troops[0][trr];
							t.total[0] -= t.troops[0][trr];
							t.active[1][tr] -= parseInt(CombatOptions.ratio[1][tr][trr]* t.troops[0][trr]);
							t.troops[0][trr] = 0;
						} else {
							t.lost[0][trr] += killed;
							t.total[0] -= killed;
							t.troops[0][trr] -= killed;
							t.active[1][tr] = 0;
						}
					}
					count++;
				}
			}
			t.c_rounds();
	},
	c_attack: function(tr,side){
		var t = myBO.Combat;
		var att = t.stats[tr][1];
		if(CombatOptions.research[side].tch8) //Add Poison Edge
			att += t.stats[tr][1]*parseFloat(CombatOptions.research[side].tch8*5/100);
		if(CombatOptions.guardian[side][0] == 'ore' && side == 1){ //Add Guardian Boost
			var boost = 0;
			switch(CombatOptions.guardian[side][1]){
				case 1:
					boost = 0.02;
					break;
				case 2:
					boost = 0.04;
					break;
				case 3:
					boost = 0.06;
					break;
				case 4:
					boost = 0.08;
					break;
				case 5:
					boost = 0.12;
					break;
				case 6:
					boost = 0.16;
					break;
				case 7:
					boost = 0.20;
					break;
				case 8:
					boost = 0.26;
					break;
				case 9:
					boost = 0.32;
					break;
				case 10:
					boost = 0.40;
					break;
				default:
					boost = 0;
			}
			att += t.stats[tr][1]*boost;
		}
		if(CombatOptions.knt[side]) //Add knight boost
			att += t.stats[tr][1]*parseFloat((CombatOptions.knt[side]/2)/100);
		return att;
	},
	c_defense: function(tr,side){
		var t = myBO.Combat;
		var def = t.stats[tr][2];
		if(CombatOptions.research[side].tch9) //Add Metal Alloy
			def += t.stats[tr][2]*parseFloat(CombatOptions.research[side].tch9*5/100);
		if(CombatOptions.knt[side]) //Add knight boost
			def += t.stats[tr][2]*parseFloat((CombatOptions.knt[side]/2)/100);
		return def;
	},
	c_life: function(tr,side){
		var t = myBO.Combat;
		var life = t.stats[tr][0];
		if(CombatOptions.research[side].tch15) //Add Healing Potions
			life += t.stats[tr][0]*parseFloat(CombatOptions.research[side].tch15*5/100);
		if(CombatOptions.guardian[side][0] == 'wood' && side == 0){ //Add Guardian Boost
			var boost = 0;
			switch(CombatOptions.guardian[side][1]){
				case 1:
					boost = 0.01;
					break;
				case 2:
					boost = 0.02;
					break;
				case 3:
					boost = 0.03;
					break;
				case 4:
					boost = 0.04;
					break;
				case 5:
					boost = 0.06;
					break;
				case 6:
					boost = 0.08;
					break;
				case 7:
					boost = 0.10;
					break;
				case 8:
					boost = 0.13;
					break;
				case 9:
					boost = 0.16;
					break;
				case 10:
					boost = 0.20;
					break;
				default:
					boost = 0;
			}
			life += t.stats[tr][0]*boost;
		}

		return life;
	},
	print: function (){
		var t = myBO.Combat;
		var m = '<div class=boStat>Resultat de la simulation</div><table width=100%><TR><td><b>Unit&eacute;</td><TD colspan=1><b>'+uW.g_js_strings.commonstr.attacker+'</b></td><td><b>Tuer</td><TD><b>D&eacute;fenseur</b></td><td><b>Tuer</td><TD><b>Nb Tours :'+t.round+'</td></TR>';
		for(var tr in unsafeWindow.unitcost){
			var name = unsafeWindow.unitcost[tr][0];
			m+='<tr><td>'+name+' :</td><td>'+ t.troops[1][tr] +'</td><td>'+t.lost[1][tr]+'</td><td>'+ t.troops[0][tr] +'</td><td>'+t.lost[0][tr]+'</td></tr>';
		}
		m+='</table>';
		ById('pbcombat_rslt').innerHTML = m;
	},
	hide: function(){},
}


myBO.Spam = {
  cont : null,
  timer : null,  
  
  init : function (){ 
    var t = myBO.Spam;
    t.cont = document.createElement('div');
     return t.cont;
 },
    getContent : function (){
   	    var t = myBO.Spam;
   	    return t.cont;
 },
  show : function (){ 
    var t = myBO.Spam;
    
        var m = '<DIV class=boStat>SPAM - CONFIGURATION</div><TABLE class=pbTab width=100% height=0% ><TR align="center">';
    
           if (Options.spamconfig.aspam == true) {
            m += '<TD><INPUT id=pbSpamEnable type=submit value="Spam On"></td>';
           }
           else {
            m += '<TD><INPUT id=pbSpamEnable type=submit value="Spam Off"></td>';
           }
    
           if (Options.spamconfig.spamstate == 'a') {
            m += '<TD><INPUT id=pbSpamState type=submit value="Actuellement sur le Chat Alliance"></td>';
           }
           else {
            m += '<TD><INPUT id=pbSpamState type=submit value="Actuellement sur le Chat Global"></td>';
           }
            m += '</tr></table></div>';
           m += '<DIV class=boStat>OPTIONS</div><TABLE class=pbTab>';
            m += '<tr><td>Poster automatiquement toutes les <INPUT id=pbSpamMin type=text size=2 maxlength=3 value="'+ Options.spamconfig.spammins +'"  \> minutes</td></tr><BR>\
                  <tr><TD><TABLE cellpadding=0 cellspacing=0>\
                  <TD align=left>Votre spam : &nbsp; </td><TD><INPUT id=pbSpamAd type=text size=60 maxlength=250 value="'+ Options.spamconfig.spamvert +'" \></td></tr>\
                  </table><BR>';
        
        t.cont.innerHTML = m;
    
        ById('pbSpamEnable').addEventListener ('click', function(){t.toggleon(this);}, false);
        ById('pbSpamAd').addEventListener ('change', t.e_spamOptChanged, false);
        ById('pbSpamMin').addEventListener ('change', t.e_spamOptChanged, false);
    ById('pbSpamState').addEventListener ('click', function(){t.togglespam(this);}, false);

  },
  hide : function (){  
    var t = myBO.Spam;
  },
  

 e_spamOptChanged : function (){
  var t = myBO.Spam;
  Options.spamconfig.spamvert = ById('pbSpamAd').value;
  Options.spamconfig.spammins = ById('pbSpamMin').value;
  if(parseInt(Options.spamconfig.spammins) < 30){
   Options.spamconfig.spammins = 30;
   ById('pbSpamMin').value = 30;
  }
  saveOptions ();
 },

 togglespam: function(obj){
  var t = myBO.Spam;
  if (Options.spamconfig.spamstate == 'a') {
   Options.spamconfig.spamstate = 'g';
   obj.value = "Actuellement sur le Chat Global";
  }
  else {
   Options.spamconfig.spamstate = 'a';
   obj.value = "Actuellement sur le Chat Alliance";
  }
  saveOptions ();

 },

 toggleon: function(obj){
  var t = myBO.Spam;
  if (Options.spamconfig.aspam == true) {
   Options.spamconfig.aspam = false;
   obj.value = "Spam Off";
  }
  else {
   Options.spamconfig.aspam = true;
   obj.value = "Spam On";
   SpamEvery.init();
  }
  saveOptions ();

 },
};  

var SpamEvery  = {
  timer : null,
  spamtimer : 0,
  init : function (){
    if (!Options.spamconfig.aspam) return;
    if (Options.spamconfig.spammins < 30)
      Options.spamconfig.spammins = 30;
    SpamEvery.setEnable (Options.spamconfig.aspam);
  },
  setEnable : function (tf){
    var t = SpamEvery;
    clearTimeout (t.timer);
    if (tf)
      t.timer = setTimeout (t.count, 60*1000);
  },
  count : function (){
   var t = SpamEvery;
   t.spamtimer = Options.spamconfig.spammins;
   if(parseInt(t.spamtimer) < 30) t.spamtimer = 30;
   if (Options.spamconfig.atime > t.spamtimer) {
    Options.spamconfig.atime = 2;
    t.doit ();
   } else {
    Options.spamconfig.atime = (Options.spamconfig.atime + 1);
    SpamEvery.init ();
   }
   saveOptions ();
  },
  doit : function (){
    sendChat ("/" + Options.spamconfig.spamstate + " " +  Options.spamconfig.spamvert);
    SpamEvery.init ();
  }
}
/*********************************** Log Tab ***********************************/
myBO.ActionLog = {
  tabOrder: 130,
  tabLabel : 'Log',
  myDiv : null,
  logTab : null,
  maxEntries: 200,
  last50 : [],
  state : null,
   init : function (){    // called once, upon script startup
 
        this.myDiv = document.createElement('div');
 
    
    return this.myDiv;
  },
  show : function (div){
    var t = myBO.ActionLog;
    
        t.myDiv = this.myDiv;
        t.myDiv.innerHTML = '<DIV  class=boStat>SUIVI ACTIVITE - LOG DE LA BOITE</div><DIV style="height:535px; max-height:535px; overflow-y:auto">\
       <select id=BOSuiviFiltre><option value="">Tout Voir</option><option value="Erreur">Autre Erreur</option><option value="Rapport">Suppression Rapport</option><option value="Transport">Transport auto</option><option value="Appro">Approvisonner</option><option value="AutoForm">Auto Formation</option><option value="Reassign">Reassigne Auto</option><option value="AutoFO">AutoFO</option><option value="RAID">Raid</option><option value="AutoTS">Auto Armoiries</option></select>\
       &nbsp;<input type=button value="nettoyer" id=BOLogClean><br><TABLE cellpadding=0 cellspacing=0 id=BOactionlog class=pbTabLined></table></div>';
     t.logTab = ById('BOactionlog');  
     t.filtre = ById('BOSuiviFiltre'); 
     t.state = 1;
     t.filtre.addEventListener ('change', t.pouette, false);
     ById('BOLogClean').addEventListener ('click', t.deleteall, false);
   
    t.pouette();
  },
  deleteall: function() {
    var t = myBO.ActionLog;
    GM_setValue ('log_'+getServerId(), '[]');
     t.pouette();
  },
  pouette: function() {
    var t = myBO.ActionLog;
    t.logTab.innerHTML="<TR><TD></td><td></td><TD width=95%></td></tr>";
      var a = JSON2.parse(GM_getValue ('log_'+getServerId(), '[]'));
      if (matTypeof(a) == 'array'){
        t.last50 = a;
        for (var i=0; i<t.last50.length; i++) {
           if (t.filtre.value=="" || t.filtre.value==t.last50[i].ou) {
           t._addTab (t.last50[i].msg, t.last50[i].ou, t.last50[i].ts);      
          }
  
        }
    }
  
  },
  hide : function (){
  },
  getContent : function (){
      return myBO.ActionLog.myDiv;
  },  
  _addTab : function (msg, ou, ts){
    var t = myBO.ActionLog;
    if (t.state != 1)
      return;
    if (t.logTab.rows.length >= t.maxEntries)
      t.logTab.deleteRow(t.maxEntries-1);
    var row = t.logTab.insertRow(0);
    row.vAlign = 'top';
    row.insertCell(0).innerHTML = ts;
    row.insertCell(1).innerHTML = ou;
    row.insertCell(2).innerHTML = msg;
  },
  
  log : function (msg,ou){
    var t = myBO.ActionLog;
    var ts = new Date().toTimeString().substring (0,8);
    if (t.filtre) {
     if (t.filtre.value=="" || t.filtre.value==ou) {
      t._addTab (msg, ou, ts);
     }  
    }else {
    t._addTab (msg, ou, ts);
    }
    while (t.last50.length >= 50)
      t.last50.shift();
    t.last50.push ({msg:msg, ts:ts, ou:ou});
    GM_setValue ('log_'+getServerId(), JSON2.stringify(t.last50));
  },
}

function actionLog (ou,msg){
    myBO.ActionLog.log (msg,ou);  
}
   
    
/*********************************** Throme TAB ***********************************/
myBO.Trone = {
  myDiv : null,
  cont : null,
  passage:null,
  timer : null, 
  filtre:"",
  tableau:[],
  filtre2:"",
  filtre3:"",
  filtre4:Options.AllEffet,
  filtre5:Options.EffetRouge,
  init : function (){ 
    this.myDiv = document.createElement('div');
    return this.myDiv;
  },

  hide : function (){
    var t = myBO.Trone;
    
  },
  getContent : function (){
      return myBO.Trone.myDiv;
  },

  show : function (){
     var t = myBO.Trone;
     unsafeWindow.BOsalvage=t.salvage;
     unsafeWindow.BOequipItem=t.equipItem;
     unsafeWindow.BOUnequipItem=t.UnequipItem;
     t.cont = this.myDiv;
     var m="";
     var k=Seed.throne.slotEquip[Seed.throne.activeSlot],i=Seed.throne.inventory,e,faction;
     var i = unsafeWindow.kocThroneItems;
     if (t.passage==null) {
      t.passage=1;
     var taille = uW.screen.height - mainPop2.getLocation().y - 450; //635px
     m+= '<DIV class=boStat><b>SALLE DU TRONE&nbsp;<input type=button value="?" id=boaidetrone class=boAide></b></div><TABLE class=pbTab width=750><tr><td></table><TABLE class=pbTab width=98%><TR align="center">';
     
      if (Options.salvageconfig.running == true) {
                 m += '<TD><INPUT id=BOTroneSalvageEnable type=submit value="Salvage Auto On"></td>';
                }
                else {
                 m += '<TD><INPUT id=BOTroneSalvageEnable type=submit value="Salvage Auto Off"></td>';
           }
           m+='<td style="text-align:right">Supportez la boite, cliquez sur la pub :</td><td rowspan=2 style="text-align:right"><iframe src=http://beworld.perso.sfr.fr/bao/pub/google.php width=320 marginwidth=0 marginheight=0 height=50 scrolling=no frameborder=0></iframe></td><tr><td>Interval : <INPUT id=BOTroneSalvageMin type=text size=2 maxlength=3 value="'+ Options.salvageconfig.mins +'"  \> minutes</td>';
           m+='<td><select id=BOTroneSalvageType><option value="0">Simple</option><option value="1">Simple + Common</option><option value="2">Simple + Common + UnCommon</option></select></td>';
      m += '</tr></table>';
      
      m += '<DIV class=boStat><b>INVENTAIRE - <span id=BONbArticle></span></b></div>Famille : <select id=BOFiltreST><option value="">Tous</option><option value="briton">briton</option><option value="druid">druid</option><option value="fey">fey</option></select>\
         Type : <select id=BOFiltre3ST><option value="">Tous</option><option value="advisor">advisor</option><option value="banner">banner</option><option value="chair">chair</option><option value="table">table</option><option value="window">window</option></select>\
         Qualit&eacute : <select id=BOFiltre2ST><option value="">Tous</option><option value="0">Simple</option><option value="1">Commun</option><option value="2">Peu Frequent</option><option value="3">Rare</option><option value="4">Epic</option><option value="5">Merveilleux</option></select>\
         <br><input type=checkbox id=BOFiltre4ST> Montrer tout les effets - Effets en rouge : <select id=BOlisteeffets></select><br>';
      m+='<DIV id=BOTroneC style="height:'+taille+'px; max-height:'+taille+'px; overflow-y:auto"></div>';
      t.cont.innerHTML = m; 
       ById('boaidetrone').addEventListener('click', function(){
      	       	 window.open(sitesupport+"?page=aide_trone");
    	} , false);
      }
      
      m='<center><table style="background-color:transparent;max-width:95%;width:95%;" cellspacing=0 cellpadding=2><tr><td colspan=1><b>Nom</td><td><b>Qualit&eacute;</td><td><b>Nom</td>\
         <td><b>Famille</td>\
         <td><b>Type</td><td><b>Effets</td><td><b>Action(s)</td></tr>';
     nb=0;
     var sl=0;
     t.tableau=[];
     for (var z in i) {
           if (i[z].id) {
            e=unsafeWindow.kocThroneItems[i[z].id];
            if (e) {
              
              t.tableau[sl]=i[z].id;
              sl++
            }
           }
     }
     var lignauto = Seed.throne.rowNum * 5;
     t.tableau.reverse();
      var pastoucher = [];
       for (var nbslot=1;nbslot<=Seed.throne.slotNum;nbslot++) {
        B = Seed.throne.slotEquip[nbslot];
        for (var zzz in B) {
         if (unsafeWindow.kocThroneItems[B[zzz]]) {
          pastoucher.push(B[zzz]);
         }
        }
       } 
     var nbl=t.tableau.length+1;
     for (var z=0;z<t.tableau.length;z++) {
       e=unsafeWindow.kocThroneItems[t.tableau[z]];
       nb++
       faction=e.faction;
       x=0;
 	nbl--;
       
       if ( (t.filtre=="" || t.filtre==faction) && (t.filtre2=="" || t.filtre2==e.quality) && (t.filtre3=="" || t.filtre3==e.type) )  {
       
       
       
       
       if (e.isEquipped) 
        equip="equip";
       else
        equip="normal";
        
        var styleez="";
        if (pastoucher.toString().indexOf(t.tableau[z])>-1 && equip=="normal") 
           styleez="'background-color:#99DC99'";
        m+="<tr><td style="+styleez+"><img title='"+e.name+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+ faction.replace('briton','britton') +"/"+ faction.replace('briton','britton') +"_"+e.type+"_"+equip+"_1.png></td>\
        <td style="+styleez+">"+ e.createPrefix() + "</td><td style="+styleez+">"+ e.createSuffix() + "</td><td style="+styleez+">"+e.faction+"</td><td style="+styleez+"> "+e.type+"</td>";
        
        m+="<td style="+styleez+">";
        for (var u in e.effects) {
           x++;
           if ((e.quality >= x && !t.filtre4) || t.filtre4) {
          var coleur="";
          var stylee="";
          if (e.quality < x) 
           stylee="text-decoration:line-through";
         if (t.filtre5==e.effects[u].id) coleur="#AA1111";
         m+="<span style='"+stylee+"'><font color="+coleur+">" + unsafeWindow.cm.thronestats.tiers[e.effects[u].id][e.effects[u].tier].base + "% " + unsafeWindow.cm.thronestats.effects[e.effects[u].id][1]+ "</font></span><bR>";
         }
        }
        m+="</td>";
        if (nbl<=lignauto) {
         m+="<td style="+styleez+"><a onclick='BOsalvage("+t.tableau[z]+")' class='buttonv2 h20 brown'>Supprimer</a>";
          if (equip=="normal")
           m+="&nbsp;<a onclick='BOequipItem("+t.tableau[z]+")' class='buttonv2 h20 blue'>Equiper</a></td></tr>";
          else
           m+="&nbsp;<a onclick='BOUnequipItem("+t.tableau[z]+")' class='buttonv2 h20 blue'>D&eacute;s&eacute;quiper</a></td></tr>";
         } else {
           m+="<td style="+styleez+">Faut acheter des lignes ^^</td></tr>";
         }
        }
     }
     m+="</table><DIV class=boStat><b>SALLE DU TRONE - STAT</b></dIV><center>";
     var B=0, w={}, x;
          for (var K in k) {
           var F = unsafeWindow.kocThroneItems[k[K]];
           if (F) {
           x=0;
           for (var M in F.effects) {
           x++;
           if (F.quality >= x) {
            B++;
            I = unsafeWindow.cm.thronestats.effects[F.effects[M].id];
            z = unsafeWindow.cm.thronestats.tiers[F.effects[M].id][F.effects[M].tier];
            C = + z.base + F.level * + z.growth;
            if (!w[F.effects[M].id]) {w[F.effects[M].id] = {};}
	                if (!w[F.effects[M].id].percent) {
	                 w[F.effects[M].id].percent = C;
	                } else {
	                 w[F.effects[M].id].percent += C;
	                }
             w[F.effects[M].id].name = I[1];
             }
            }
           }
          }
        B = 0;
        for (var K in w) {
            
            G="<b>"+ w[K].percent + "% </b>" + w[K].name + "<br>";
            
             m+=G;
         }
   
    m+="</table></div>";
    ById("BOTroneC").innerHTML=m; 
     
     // liste des effets :
     var liste = uW.cm.thronestats.effects;
     ById("BOlisteeffets").innerHTML="";
     var o = document.createElement("option");
     o.text = "----";
     o.value = 0;
     ById("BOlisteeffets").options.add(o);
     for (k in liste){
         if (liste[k] !=undefined){
             	    			var o = document.createElement("option");
             	    			o.text = liste[k][1];
             	    			o.value = k;
             	    			ById("BOlisteeffets").options.add(o);
         }
     }
     ById('BOlisteeffets').value=t.filtre5;
     ById("BOlisteeffets").addEventListener ('change', t.filtreaction, false);
     ById("BONbArticle").innerHTML= nb;
     ById('BOFiltreST').value=t.filtre;
     ById('BOFiltreST').addEventListener ('change', t.filtreaction, false);
     ById('BOFiltre2ST').value=t.filtre2;
     ById('BOFiltre2ST').addEventListener ('change', t.filtreaction, false);
     ById('BOFiltre3ST').value=t.filtre3;
     ById('BOFiltre3ST').addEventListener ('change', t.filtreaction, false);
     ById('BOFiltre4ST').checked=t.filtre4;
     ById('BOFiltre4ST').addEventListener ('click', t.filtreaction, false); 
     ById('BOTroneSalvageEnable').addEventListener ('click', function(){t.toggleon(this);}, false);
     ById('BOTroneSalvageType').value=Options.salvageconfig.typeselect;
     ById('BOTroneSalvageType').addEventListener ('change', function(){
       Options.salvageconfig.typeselect = ById('BOTroneSalvageType').value;
       saveOptions ();
     }, false);
     ById('BOTroneSalvageMin').addEventListener ('change', function(){
       if (parseIntNan(ById('BOTroneSalvageMin').value) < 10) ById('BOTroneSalvageMin').value=10;
       Options.salvageconfig.mins = ById('BOTroneSalvageMin').value;
       saveOptions ();
     }, false);
  },
  toggleon: function(obj){
    var t = myBO.Trone;
    if (Options.salvageconfig.running == true) {
     Options.salvageconfig.running = false;
     if (obj) obj.value = "Salvage Auto Off";
    }
    else {
     Options.salvageconfig.running = true;
     if (obj) obj.value = "Salvage Auto On";
     SalvageAuto.init();
    }
    saveOptions ();
 },
  filtreaction: function() {
    var t = myBO.Trone;
    t.filtre = ById('BOFiltreST').value;
    t.filtre2 = ById('BOFiltre2ST').value;
    t.filtre3 = ById('BOFiltre3ST').value;
    t.filtre4 = ById('BOFiltre4ST').checked;
    t.filtre5 = ById('BOlisteeffets').value;
    Options.EffetRouge = t.filtre5;
    Options.AllEffet = t.filtre4;
    saveOptions ();
    t.show();

  },
  equipItem: function(id) {
   var t = myBO.Trone;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
   params.action="equipItem";
   params.ctrl="throneRoom\\ThroneRoomServiceAjax";
   params.itemId=id; 
   params.presetId=Seed.throne.activeSlot;
   unsafeWindow.ajax.Request(unsafeWindow.g_ajaxpath+"ajax/_dispatch53.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
    onSuccess:function(transport) {
     var m = eval("(" + transport.responseText + ")");
     if (m.ok === true){
      unsafeWindow.cm.ThroneView.clickItemEquip(unsafeWindow.kocThroneItems[id]);
      t.show();
     }
    }
   });
  },
  UnequipItem: function(id) {
     var t = myBO.Trone;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
     params.action="unequipItem";
     params.ctrl="throneRoom\\ThroneRoomServiceAjax";
     params.itemId=id; 
     params.presetId=Seed.throne.activeSlot;
     unsafeWindow.ajax.Request(unsafeWindow.g_ajaxpath+"ajax/_dispatch53.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
      onSuccess:function(transport) {
       var m = eval("(" + transport.responseText + ")");
       if (m.ok === true){
        unsafeWindow.cm.ThroneView.clickItemUnequip(unsafeWindow.kocThroneItems[id]);
        t.show();
       }
      }
     });
  },
  salvage: function(id) {
   var t = myBO.Trone;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
   params.action="salvage";
   params.ctrl="throneRoom\\ThroneRoomServiceAjax";
   params.itemId=id; 
   params.cityId=unsafeWindow.currentcityid;
   unsafeWindow.ajax.Request(unsafeWindow.g_ajaxpath+"ajax/_dispatch53.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
    onSuccess:function(transport) {
     var m = eval("(" + transport.responseText + ")");
     if (m.ok){ 
      unsafeWindow.kocThroneItems[id].salvage();
      t.show();
     }
    }
   });
  }
}

var SalvageAuto  = {
  timer : null,
  salvagetimer : 0,
  tableau:[],
  init : function (){
    if (!Options.salvageconfig.running) return;
    SalvageAuto.setEnable();
  },
  setEnable : function (){
    var t = SalvageAuto;
    clearTimeout (t.timer);
    clearTimeout (t.salvagetimer);
    t.tableau=[];
    t.timer = setTimeout (t.count, 5*1000);
  },
  count : function (){
   var t = SalvageAuto;
   var k=Seed.throne.slotEquip[Seed.throne.activeSlot],i=unsafeWindow.kocThroneItems,e,faction;
   var lignauto = Seed.throne.rowNum * 5;
   var nbl=0;
   for (var z in i) {
     if (i[z].id) {
       e=unsafeWindow.kocThroneItems[i[z].id];
       if (e) {
	nbl++;
	if (nbl<=lignauto && e.quality<=Options.salvageconfig.typeselect && !e.isEquipped && e.level==0) {
	 t.tableau.push(i[z].id);
	 
	}
	
       }
      }
   }
   if (t.tableau.length>0) {
    //actionLog("SalvageAuto","Lancement de l'auto suppression des articles");
    t.doit();
   }
   t.timer = setTimeout (t.count, (Options.salvageconfig.mins*60)*1000);
  },
  doit : function (){
    var t = SalvageAuto; 
    if (t.tableau.length>0) {
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
         params.action="salvage";
         params.ctrl="throneRoom\\ThroneRoomServiceAjax";
         params.itemId=t.tableau[t.tableau.length-1]; 
         params.cityId=unsafeWindow.currentcityid;
         unsafeWindow.ajax.Request(unsafeWindow.g_ajaxpath+"ajax/_dispatch53.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,loading:false,
          onSuccess:function(transport) {
           var m = eval("(" + transport.responseText + ")");
           if (m.ok===true){ 
            var name=unsafeWindow.kocThroneItems[t.tableau[t.tableau.length-1]].name;
            actionLog("SalvageAuto","Suppression reussi :" + name);
            unsafeWindow.kocThroneItems[t.tableau[t.tableau.length-1]].salvage();
            
            t.tableau.pop();
            t.salvagetimer = setTimeout(function() { t.doit(); } , 6000);
           } else {
            actionLog("SalvageAuto","<font color=red>Suppression en erreur</font> - Arret de la suppression auto");
            //myBO.Trone.toggleon(ById('BOTroneSalvageEnable'));
           }
          }
     });
   } else {
     t.tableau=[];
     clearTimeout (t.salvagetimer);
    }
  },
  

  
}
/*********************************** Test TAB ***********************************/
myBO.Test = {
  tabOrder: 25,
  tabDisabled : false,        
  tabLabel : 'Test',
  myDiv : null,
  cont : null,
 
  init : function (){    // called once, upon script startup
    this.myDiv = document.createElement('div');
    return this.myDiv;
  },

  hide : function (){
    var t = myBO.Test;
  },
  getContent : function (){
      return myBO.Test.myDiv;
  },
  show : function (){
     var t = myBO.Test;
     t.cont = this.myDiv;
     var citySelect = '   <SELECT id=fakeCity>';
     	    for (var c=0; c<Cities.numCities; c++) {
     		 	 aCity = Cities.cities[c].name + ' ('+Cities.cities[c].x + ','+ Cities.cities[c].y+')';
     	         citySelect += '<option value=\''+c+'\'>'+aCity+'</option>';
     	    }
	    citySelect += '</select>';
     
     
  var m = '<DIV class=boStat><b>TEST DES ALERTES - DETECTION DES ATTAQUES</b></div><TABLE><TR><TD align=right>Eclairage</td><TD><INPUT type=checkbox id=fakeIsScout></td><TD align=right>Terre Sauvage</td><TD><INPUT type=checkbox id=fakeIsWild></td></tr>\
        <TR><TD colspan=2 align=right>Dur&eacute;e (Secondes) : </td><TD><INPUT type=text size=4 value=300 id=fakeSeconds></td></tr>\
        <TR><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt1'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_1_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop0></td><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt2'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_30_s34.jpg></td><TD><INPUT type=text size=6 value=1 id=faketroop1></td></tr>\
	<TR><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt3'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop2></td><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt4'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop3></td></tr>\
	<TR><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt5'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop4></td><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt6'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop5></td></tr>\
	<TR><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt7'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_7_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop6></td><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt8'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_8_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop7></td></tr>\
	<TR><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt9'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop8></td><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt10'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop9></td></tr>\
	<TR><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt11'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop10></td><TD align=right><img height=18 title="'+unsafeWindow.unitcost['unt12'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_30_s34.jpg></td><TD><INPUT type=text size=6 value=0 id=faketroop11></td></tr>\
	<TR><TD align=right>'+uW.g_js_strings.commonstr.attacker+'</td><TD><INPUT type=text size=13 value="Kabam!" id=fakeName></td><td align=right>'+uW.g_js_strings.commonstr.might+'</td><td><INPUT type=text size=13 value="5441192" id=fakeMight></td></tr>\
	<TR><TD align=right>'+uW.g_js_strings.commonstr.target+'</td><TD>'+citySelect+'</td><td><INPUT id=testSendMarch type=submit value="Fausse Attaque" \></td></tr>';
   m+='</td></tr></table><br><hr>Autres Options :<br><INPUT id=ptReloadKOC type=submit value="Recharger KOC" \>\
        <BR><DIV id=testDiv style="background-color:#fffff0; maxwidth:675; max-height:30px; height:0px; overflow-y:auto;"></div>';
    t.cont.innerHTML = m;
    
     ById('testSendMarch').addEventListener ('click', t.clickFakeAttack, false);
    ById('ptReloadKOC').addEventListener ('click', t.reloadKOC, false);
  
    function xyNotify(city, x, y){
      var m = '[ Notified: '+ (city?city.name:'null') +', x='+ x +', y='+ y +' ]';
      ById('testNotify').innerHTML = m;
    }
   
  },
  writeDiv : function (msg){
    var t = myBO.Test;
    if (t.state != null)
    ById('testDiv').innerHTML = msg;
  },

  addDiv : function (msg){
    var t = myBO.Test;
    if (t.state != null)
    ById('testDiv').innerHTML += msg;
  },
  
  reloadKOC : function (){
   
      reloadKOC();
  },
  
  createFakeAttack : function (cityNum, isScout, isWild, isFalse, secs, troops, name, might){
     var marchId = 'm'+ (88888 + Math.floor(Math.random()*11111));
     var march = {};
     if (matTypeof(Seed.queue_atkinc)=='array')
       Seed.queue_atkinc = {};
     if (isFalse)
       march.marchType = 0;
     else if (isScout)
       march.marchType = 3;
     else
       march.marchType = 4;
 
     march.toCityId = Cities.cities[cityNum].id;
     if (isWild) {
       keys = unsafeWindow.Object.keys(Seed.wilderness['city'+Cities.cities[cityNum].id]);
       march.toTileId = Seed.wilderness['city'+Cities.cities[cityNum].id][keys[0]].tileId;
     } else {
       march.toTileId = Cities.cities[cityNum].tileId;
     }
     secs = parseInt(secs);
     march.arrivalTime = unixTime() + secs;
     march.departureTime = unixTime() - 10;
      march.unts = {}
 	for(i=0; i<12; i++){
 	  if(troops[i] > 0)
 		march.unts["u"+(i+1)] = addCommas(troops[i]);
 	}
     march.pid = 1234567;
     march.score = 9;
     march.mid = marchId.substr(1);
     march.players = {}
     march.players.u1234567 = {}
     march.players.u1234567.n = name;
     march.players.u1234567.t = 60;
     march.players.u1234567.m = might;
     march.players.u1234567.s = 'M';
     march.players.u1234567.w = 1;
     march.players.u1234567.a = 1;
     march.players.u1234567.i = 5;
     Seed.queue_atkinc[marchId] = march;
     Seed.players.u1234567 = march.players.u1234567;
   },
 
   clickFakeAttack : function (){
     var t = myBO.Test;
     var isScout = ById('fakeIsScout').checked;
     var isWild = ById('fakeIsWild').checked;
     var isFalse = false;
 	var troops = [];
 	for(i=0; i<12; i++)
 		troops[i] = parseInt(ById('faketroop'+i).value);
     var secs = parseInt(ById('fakeSeconds').value);
 	var name = ById('fakeName').value;
 	var city = ById('fakeCity').value;
 	var might = ById('fakeMight').value;
     t.createFakeAttack (city, isScout, isWild, isFalse, secs, troops ,name,might);
   },
}


/************ DEBUG WIN *************/
var debugWin = {
	popDebug:			null,
	dbDefaultNot:	'tech,tutorial,items,quests,wilderness,wildDef,buildings,knights,allianceDiplomacies,appFriends,players',
	dbSelect:			{},
	sortSeed:			[],
	sortNonSeed:	[],

	doit: function (){
		var t = debugWin;

		function syncBoxes (){
			for (var i=0; i<t.sortSeed.length; i++){
				var name = t.sortSeed[i];
				var box = document.getElementById('dbpop_'+name);
				box.checked = t.dbSelect[name];
			}
		}
		function clickedAll (){
			for (var k in t.dbSelect)
				t.dbSelect[k] = true;
			syncBoxes();
		}
		function clickedNone (){
			for (var k in t.dbSelect)
				t.dbSelect[k] = false;
			syncBoxes();
		}
		function clickedDefaults (){
			for (k in t.dbSelect)
				t.dbSelect[k] = true;
			var not = t.dbDefaultNot.split(',');
			for (var i=0; i<not.length; i++)
				t.dbSelect[not[i]] = false;
			syncBoxes();
		}
		function clickedShow (){
			var resultsDiv = document.getElementById('idDebugResultsDiv')
			var s = '<PRE>';
			for (var i=0; i<t.sortSeed.length; i++){
				var name = t.sortSeed[i];
				var box = document.getElementById('dbpop_'+name);
				if (box.checked)
					s += name + " =\n" + inspect (Seed[name], 10, 1);
			}
			resultsDiv.innerHTML = s + '</PRE>';
		}

		function clickedShowNonSeed (){
			var resultsDiv = document.getElementById('idDebugResultsDiv');
			nsvalue = document.getElementById('dbnonseed').value;
		;
			if (nsvalue != '') {
				val = unsafeWindow[nsvalue];
				valtype = typeof(val);
				resultsDiv.innerHTML = '<textarea cols=80 rows=40>(' + valtype + ') ' + nsvalue + ((valtype == 'string')?(" = " + val):(" =\n" + inspect (val, 15, 1,true))) + '</textarea>';
			}
		
		}

		function clickedShowScripts (){
			var resultsDiv = document.getElementById('idDebugResultsDiv')
			var scripts = document.getElementsByTagName('script');
			var s = '';
			for (var i=0; i<scripts.length; i++)
				if (scripts[i].src!=null && scripts[i].src!='')
					s+='<A TARGET=_tab HREF="'+ scripts[i].src +'">'+ scripts[i].src +'</A><BR />';
			resultsDiv.innerHTML = s;
		}

		if (t.popDebug == null){
			t.popDebug = new CPopup ('db', 0, 45, 749, 900, true);
			t.popDebug.getTopDiv().innerHTML = '<DIV align=center><B>DEBUG</B></DIV>';
			var sl = 0;
			for (var k in Seed) {
				t.dbSelect[k] = true;
				t.sortSeed[sl] = k;
				sl++;
			}
			t.sortSeed.sort();
			sl = 0;
			for (var k in unsafeWindow) {
				kType = typeof(unsafeWindow[k]);
				/*if ((k.indexOf('actionlink_data') != 0) && (k != 'content') && (k != 'document') && (k.indexOf('feed') != 0) && (k.indexOf('frame') != 0) && (k != 'globalStorage') &&
					(k != 'g_mapObject') && (k != 'history') && (k != 'Modal') && (k != 'navigator') && (k != 'parent') && (k.indexOf('pb') != 0) && (k.indexOf('pt') != 0) && (k != 'seed') &&
					(k != 'self') && (k.indexOf('template_data') != 0) && (k != 'that') && (k != 'window') && (k != '_htmlElement') && (kType != 'function') && (kType != 'undefined')) {
				*/
				t.sortNonSeed[sl] = k;
					sl++;
				/*}*/
				
			}
		
			t.sortNonSeed.sort(function(x,y) {var a = String(x).toUpperCase(); var b = String(y).toUpperCase(); if (a > b) return 1; else if (a < b) return -1; else return 0;});
			var nsSelect = '<SELECT id="dbnonseed"><OPTION value="" ></option>';
			for (var i=0; i<t.sortNonSeed.length; i++)
				nsSelect += '<OPTION value="' + t.sortNonSeed[i] + '" >' + t.sortNonSeed[i] + '</option>';
			nsSelect += '</SELECT>';
			var not = t.dbDefaultNot.split(',');
			for (var i=0; i<not.length; i++)
				t.dbSelect[not[i]] = false;
			var m = '<DIV class=ptentry><B>Seed: </B><INPUT type=submit id=dbsuball value=ALL>&nbsp;<INPUT type=submit id=dbsubnone value=NONE>&nbsp;' +
				'<INPUT type=submit id=dbdefaults value=DEFAULTS>&nbsp;<INPUT type=submit id=dbsubdo value=SHOW>&nbsp;<INPUT type=submit id=dbsubscripts value=SCRIPTS><BR /><TABLE width=100%>';
			var cols = 5;
			var entries = t.sortSeed.length;
			var rows = parseInt (0.99 + entries / cols);
			for (var rowno=1; rowno<=rows; rowno++) {
				m += '<TR>';
				for (colno=1; colno<=cols; colno++) {
					var slvalue = rows*(colno-1)+rowno-1;
					m += ((slvalue < entries)?('<TD class=xtab><INPUT type=checkbox id="dbpop_'+t.sortSeed[slvalue]+'">&nbsp;'+t.sortSeed[slvalue]+'</TD>'):'<TD class=xtab></TD>');
				}
				m += '</TR>';
			}
			m += '</TABLE><B>Non-Seed: </B>' + nsSelect + '</DIV><DIV id="idDebugResultsDiv" style="width:738px; height:600px; max-height:600px; overflow-y:auto; white-space:pre-wrap;"></DIV>';
			t.popDebug.getMainDiv().innerHTML = m;
			document.getElementById('dbsuball').addEventListener('click', clickedAll, false);
			document.getElementById('dbsubnone').addEventListener('click', clickedNone, false);
			document.getElementById('dbdefaults').addEventListener('click', clickedDefaults, false);
			document.getElementById('dbsubdo').addEventListener('click', clickedShow, false);
			document.getElementById('dbsubscripts').addEventListener('click', clickedShowScripts, false);
			document.getElementById('dbnonseed').addEventListener('change', clickedShowNonSeed, false);
			syncBoxes();
		}
		t.popDebug.show (true);
	},
}

function inspect(obj, maxLevels, level, doFunctions){
  var str = '', type, msg;
  if(level == null)  level = 0;
  if(maxLevels == null) maxLevels = 1;
  if(maxLevels < 1)
      return 'Inspect Error: Levels number must be > 0';
  if(obj == null)
    return 'ERROR: Object is NULL\n';
  var indent = '';
  for (var i=0; i<level; i++)
    indent += '  ';
  for(property in obj) {
    //logit(property);
    try {
        type =  matTypeof(obj[property]);
        if (doFunctions==true && (type == 'function')){
          str += indent + '(' + type + ') ' + property + "[FUNCTION]\n   " + ( (obj[property]==null)?(': null'):('')) +' = '+ obj[property] +"\n";
        } else if (type != 'function') {
          str += indent + '(' + type + ') ' + property + ( (obj[property]==null)?(': null'):('')) +' = '+ obj[property] +"\n";
        }
        if((type=='object' || type=='array') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1, doFunctions);  // recurse
          
        //if (doFunctions==true && (type == 'function') && (obj[property] != null) && (level+1 < maxLevels))
        // str += inspect(obj[property], maxLevels, level+1, doFunctions);  // recurse
    }
    catch(err) {
      // Is there some properties in obj we can't access? Print it red.
      if(typeof(err) == 'string') msg = err;
      else if(err.message)        msg = err.message;
      else if(err.description)    msg = err.description;
      else                        msg = 'Unknown';
      str += '(Error) ' + property + ': ' + msg +"\n";
    }
  }
  str += "\n";
  return str;
}
/********************************* RESUME ***********************************/
function getResourceProduction (cityId){
  var ret = [0,0,0,0,0];
  var now = unixTime ();
  
  var wilds = [0, 0, 0, 0, 0];
  var w = Seed.wilderness["city" + cityId];
  for (var k in w){
    var type = parseInt(w[k].tileType);
    if (type==10 || type==11)
      wilds[1] += parseInt(w[k].tileLevel);
    else 
      wilds[type/10] += parseInt(w[k].tileLevel);
  }  
  
  knight = 0;       
  var s = Seed.knights["city" + cityId];
  if (s) {
    s = s["knt" + Seed.leaders["city" + cityId].resourcefulnessKnightId];
    if (s){
      var knight = parseInt(s.resourcefulness);
      if (s.resourcefulnessBoostExpireUnixtime > now)
        knight *= 1.25;
    }
  }
  var workerFactor = 1;
  var c = parseInt(Seed.citystats["city" + cityId]["pop"][0]);  // Current  population
  var w = parseInt(Seed.citystats["city" + cityId]["pop"][3]);  // Labor force
  if (w > c)
    workerFactor = c / w;
  
  for (var i=1; i<5; i++){
    var usage = Seed.resources["city" + cityId]["rec" + i];
    var items = 0;
    if (parseInt(Seed.playerEffects["r" + i + "BstExp"]) > now) {
      items = 0.25;
    }
    var tech = Seed.tech["tch" + i];
    ret[i] = parseInt((usage[2] * (1 + tech/10 + knight/100 + items + 0.05 * wilds[i]) * workerFactor + 100));
  }
  return ret;  
}

function getWallInfo (cityId, objOut){
	objOut.wallSpaceUsed = 0;
	objOut.fieldSpaceUsed = 0;
	objOut.wallLevel = 0;
	objOut.wallSpace = 0;
	objOut.fieldSpace = 0;
	objOut.Crossbows = 0;
	objOut.CrossbowsTraining = 0;
	objOut.Trebuchet = 0;
	objOut.TrebuchetTraining = 0;
	objOut.Caltrops = 0;
	objOut.CaltropsTraining = 0;
	objOut.SpikedBarrier = 0;
	objOut.SpikedBarrierTraining = 0;
	objOut.Trap = 0;
	objOut.TrapTraining = 0;
	objOut.slotsBusy = 0;
	var b = Seed.buildings["city" + cityId];
	if (b.pos1==null)
		return;
	objOut.wallLevel = parseInt(b.pos1[1]);
	var spots = 0;
	for (var i=1; i<(objOut.wallLevel+1); i++)
		spots += (i * 500);
	objOut.wallSpace = spots;
	objOut.fieldSpace = spots;

	var fort = Seed.fortifications["city" + cityId];
	for (k in fort){
		var id = parseInt(k.substr(4));
		if (id == 53)
			objOut.Crossbows = parseInt(fort[k]);
		else if (id == 55)
			objOut.Trebuchet = parseInt(fort[k]);
		else if (id == 60)
			objOut.Trap = parseInt(fort[k]);
		else if (id == 61)
			objOut.Caltrops = parseInt(fort[k]);
		else if (id == 62)
			objOut.SpikedBarrier = parseInt(fort[k]);
		if (id<60)
			objOut.wallSpaceUsed += parseInt(unsafeWindow.fortstats["unt"+ id][5]) * parseInt(fort[k]);
		else
			objOut.fieldSpaceUsed += parseInt(unsafeWindow.fortstats["unt"+ id][5]) * parseInt(fort[k]);
	}
	var q = Seed.queue_fort["city"+cityId];
	if (q && q.length>0) {
		for (qi=0; qi<q.length; qi++) {
			objOut.slotsBusy++;
			if (q[qi][0]==53)
				objOut.CrossbowsTraining += parseInt(q[qi][1]);
			if (q[qi][0]==55)
				objOut.TrebuchetTraining += parseInt(q[qi][1]);
			if (q[qi][0]==60)
				objOut.TrapTraining += parseInt(q[qi][1]);
			if (q[qi][0]==61)
				objOut.CaltropsTraining += parseInt(q[qi][1]);
			if (q[qi][0]==62)
				objOut.SpikedBarrierTraining += parseInt(q[qi][1]);
		}
	}
}
Tabs.Overview = {
  tabOrder: 1,
  tabLabel: 'R&eacute;sum&eacute;',
  myDiv: null,

  displayTimer : null,
  checkBox:null,
  defMode : {},  
  checkBox1:null,
  Overview : function (){
  },

  init : function (div){
     
    var t = Tabs.Overview;
    unsafeWindow.BOCrafting = t.Crafting;
    unsafeWindow.BOCraftingItem = t.CraftingItem;
    t.myDiv = div;  
    var str= '<div id="BOResumeDIV" style="height:' + (Options.HauteurBoite-30) +'px;max-height:' + (Options.HauteurBoite-30) +'px;overflow-y:auto"></div>';
    t.myDiv.innerHTML = str;
    t.BOResumeDIV = ById("BOResumeDIV");
    
  },

  getContent : function (){

  },

  hide : function (){
   var t = Tabs.Overview;
    clearTimeout (t.displayTimer);
  },
 show : function (){
   var t = Tabs.Overview;
   clearTimeout (t.displayTimer);
   t.setContent();
 },
 CraftingItem: function (obj, currentcity, itemId, recipeId, categoryId) {
  var t = Tabs.Overview;
  if (obj) obj.value="Crafting...";
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.action="craft";
        params.ctrl="Crafting";
        params.cityId=currentcity;
        params.insurance=false;
 	params.itemId=itemId;
 	params.recipeId=recipeId;
 	params.categoryId=categoryId;
 
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                      method: "post",
       		    parameters: params,
      	onSuccess: function (transport) {
          var o=eval("("+transport.responseText+")");
          if(o.ok===true){
           if (o.status=="error") {
            alert("Erreur crafting : " + o.errorMessage);
            if (obj) obj.value="Craft";
           } else if(o.status=="failure"){
	     alert("Echec crafting !");
	     if (obj) obj.value="Craft";
	   } else if (o.status=="success"){
	     if (obj) obj.value="Craft OK";
		if(!Seed.queue_craft["city"+currentcity]) {
		 Seed.queue_craft["city"+currentcity]=[];
		}
     		var n={};
     		n.recipeId=recipeId;
     		n.craftingUnixTime=o.time.startTime;
     		n.craftingEtaUnixTime=o.time.endTime;
     		n.craftingId=o.craftingId;
     		n.categoryId=null;
     		n.recipeIndex=null;
     		unsafeWindow.seed.queue_craft["city"+currentcity].push(n);
     	  }
        } 
        t.Crafting(currentcity);
        },
         onFailure: function () {
          alert("Erreur requete crafting !");
          t.Crafting(currentcity);
         }
        });
 },
 itemscraft: {55:25000,2003:0,3000:10500,3001:5200,3002:10500,3003:10500,3004:120000,3005:180000,3006:240000,3007:2500,3008:2500,3009:2500,3010:75000,3011:21000,2002:400000,401:320000,241:50000,231:50000,211:50000,221:50000,402:500000,1120:80000,1121:85000},
 Crafting: function(currentcity) {
  var t = Tabs.Overview;
   var messagebody ="";
   var ret=getCityBuilding(currentcity,20).count;
   if (ret>0) {
     var texte="";
     var i=Seed.queue_craft["city"+currentcity];
     if(i.length>0) {
      var q=i[0];
      var totTime = 0;
      var now = unixTime();
      totTime = q.craftingEtaUnixTime - now;
      if (totTime > 0) {
         texte= "en cours...";
      }
     }
     messagebody += "<TABLE width=95% border=0 align=center class=ptTab><tr><td colspan=8><b>Objets sp&eacute;ciaux du Crafting</td></tr>";
     messagebody += "<tr><td colspan=2>Objet &agrave; cr&eacute;er</td><td>Stock</td><td>Action Manuel</td><td>Besoins</td></tr>";       
     var h=3000,qte=0;
     if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
         messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
     if (texte!="")
           messagebody += "<td>en cours...</td>";
     else
         messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",1,1)'></td>";
     messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
     messagebody +="</td></tr>";
     var h=3003,qte=0;
     if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
         messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
     if (texte!="")
           messagebody += "<td>en cours...</td>";
     else
         messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",4,1)'></td>";
     messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
     messagebody +="</td></tr>";
               var h=3007,qte=0;
              if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
                  messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
              if (texte!="")
                    messagebody += "<td>en cours...</td>";
              else
                  messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",8,1)'></td>";
              messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
         messagebody +="</td></tr>";
               var h=3008,qte=0;
              if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
                  messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
              if (texte!="")
                    messagebody += "<td>en cours...</td>";
              else
                  messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",9,1)'></td>";
              messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
         messagebody +="</td></tr>";
               var h=3009,qte=0;
              if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
                  messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
              if (texte!="")
                    messagebody += "<td>en cours...</td>";
              else
                  messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",10,1)'></td>";
              messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
          messagebody +="</td></tr>";
    
     var h=3001,qte=0;
     if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
     messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
     if (texte!="")
        messagebody += "<td>en cours...</td>";
     else
       messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",2,1)'></td>";
       messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
       messagebody +="</td></tr>";
    
     var h=3011,qte=0;
     if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
     messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
     if (texte!="")
                messagebody += "<td>en cours...</td>";
          else
              messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",12,1)'></td>";
          messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
          messagebody+="<br>Aile de Lin : 2/" +parseIntNan(Seed.items["i3001"])+"<br>Pierre Ohr : 1/" +parseIntNan(Seed.items["i3000"]);
          messagebody +="</td></tr>";
          
     var h=3010,qte=0;
     if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
     messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
     if (texte!="")
       messagebody += "<td>en cours...</td>";
     else
       messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",11,1)'></td>";
     messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"<br>Cachette animale : 2/" +parseIntNan(Seed.items["i3002"])+"<br>Armoiries Gallad : 1/" +parseIntNan(Seed.items["i1107"]);
     messagebody +="</td></tr>";                            
     
     var h=3004,qte=0;
     if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
     messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
     if (texte!="")
           messagebody += "<td>en cours...</td>";
     else
         messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",5,1)'></td>";
     messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
     messagebody +="</td></tr>";
    
    var h=3005,qte=0;
     if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
         messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
     if (texte!="")
           messagebody += "<td>en cours...</td>";
     else
         messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",6,1)'></td>";
     messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
     messagebody +="</td></tr>";
     
     var h=3006,qte=0;
          if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
              messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
          if (texte!="")
                messagebody += "<td>en cours...</td>";
          else
              messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",7,1)'></td>";
          messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h]);
     messagebody +="</td></tr>";
      
     qte=0;h=401;
     if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
     messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
     if (texte!="")
         messagebody += "<td>en cours...</td>";
       else
         messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",13,1)'></td>";
        messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"</td></tr>";
      
      qte=0;h=402;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
       messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
         messagebody += "<td>en cours...</td>";
       else
         messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",14,1)'></td>";
        messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"</td></tr>";
          
       qte=0; h=241;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
       messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
           messagebody += "<td>en cours...</td>";
       else
          messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",28,1)'></td>";
          messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"</td></tr>";

       qte=0;  h=211;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
       messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
           messagebody += "<td>en cours...</td>";
       else
          messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",27,1)'></td>";
          messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"</td></tr>";
       
       qte=0;    h=231;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
       messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
           messagebody += "<td>en cours...</td>";
       else
          messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",26,1)'></td>";
       messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"</td></tr>";
       qte=0;    
       h=221;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
       messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
           messagebody += "<td>en cours...</td>";
       else
          messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",25,1)'></td>";
       messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"<br>Heliotrope : 5/"+parseIntNan(Seed.items["i3007"])+"<br>Pierre de Keter : 2/"+parseIntNan(Seed.items["i3003"])+"</td></tr>";
       qte=0;h=55;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
       messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
           messagebody += "<td>en cours...</td>";
       else
          messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",20,3)'></td>";
       messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"<br>Aile de lin : 5/"+parseIntNan(Seed.items["i3001"])+"<br>Sire Kay : 1/"+parseIntNan(Seed.items["i1103"])+"</td></tr>";
                    
       qte=0;h=2002;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
       messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
         messagebody += "<td>en cours...</td>";
       else
         messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",29,1)'></td>";
        messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"</td></tr>";
    
       h=1120;qte=0;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
              messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
                messagebody += "<td>en cours...</td>";
       else
                messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",31,1)'></td>";
       messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"<br>Sceau de Morgane 1/"+parseIntNan(Seed.items["i1110"])+"<br>Soif de sang : 1/"+parseIntNan(Seed.items["i261"])+"<br>Heliotrope : 1/"+parseIntNan(Seed.items["i3007"])+"<br>Faveur de Guenievre : 2/"+parseIntNan(Seed.items["i3011"])+"</td></tr>"; 
       
       h=1121; qte=0;
       if (parseInt(Seed.items["i"+h])>0) qte=parseIntNan(Seed.items["i"+h]);
          messagebody += "<tr><td><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td><td>"+unsafeWindow.itemlist["i"+h].name+"</td><td><center><b>"+qte+"</td>";
       if (texte!="")
          messagebody += "<td>en cours...</td>";
       else
          messagebody += "<td><input type=button value='Craft' onclick='BOCraftingItem(this,"+currentcity+","+h+",32,1)'></td>";
       messagebody += "<td>Pierre d\'Ether : "+addCommas(t.itemscraft[h])+"<br>Aetherseal : 1/"+parseIntNan(Seed.items["i1120"])+"<br>Peau de Gargouille : 1/"+parseIntNan(Seed.items["i272"])+"<br>Oeil de Tigre : 3/"+parseIntNan(Seed.items["i3009"])+"<br>Pierre magnetique : 3/"+parseIntNan(Seed.items["i3008"])+"<br>Faveur Guenievre : 2/"+parseIntNan(Seed.items["i3011"])+"</td></tr>";   
       
       messagebody+="</table>";  
   
  } else {
   messagebody += "<center>Fl&egrave;che de Fey n\'est pas pr&eacute;sente sur cette ville !</center>";
  }
  if (t.BOPopCrafting == null) {
     	t.BOPopCrafting = new CPopup('BOPopCrafting', 0, 0, 560, 700, true, function() {clearTimeout (1000);});
     	t.BOPopCrafting.centerMe (mainPop.getMainDiv());
     	}
     	var m = '<DIV style="max-height:665px; height:665px; overflow-y:scroll">';
     	m+= messagebody + '</div>';
     	t.BOPopCrafting.getMainDiv().innerHTML = m;
     	t.BOPopCrafting.getTopDiv().innerHTML = '<DIV align=center><B>Fl&egrave;che de Fey</B></DIV>';
	t.BOPopCrafting.show(true);  

 },

 setContent : function (){

    var t = Tabs.Overview;
    var rownum = 0;
    var totalentre = 0;  
    function UniteFormation(id) {
     var nbunit=0; // 
     for(i=0; i<Cities.numCities; i++) {
      var cityIdd = Cities.cities[i].id;
      var q = Seed.queue_unt['city'+cityIdd];
      var qs = q.toString();
       if (q!=null && q.length>0 ){
        for (var ii=0; ii<q.length; ii++){
         if (q[ii][0]==id) nbunit+=parseIntNan(q[ii][1]);
         
        }
      }
      }
      totalentre += parseIntNan(nbunit*UniteCout(id));
      return nbunit;
    }
    function UniteCout(id) {
      var Unitcout=unsafeWindow.unitupkeeps[id]; 
      return Unitcout;
    }
 
    function _row (name, row, noTotal, typee){
      if (rownum++ % 2)
        style = '';
      else
        style = ' style = "background: #e8e8e8"';
      var tot = 0;
      var m = [];
      m.push ('<TR style="background: #fff" align=right');
      m.push (style);
      m.push ('><TD');
      m.push (style);
      m.push ('><B>');
      m.push (name);
      m.push ('</td>');
      if (noTotal){
        m.push ('<TD');
        m.push (style);
        m.push ('>&nbsp;</td>');
      } else {
        for (i=0; i<row.length; i++)
          tot += row[i];
        m.push ('<TD style="background: #ffc">');
         if (tot<0) {
              m.push ("<SPAN class=boldRed>"+UniteKMG(tot)+"</span>");
         } else {
	   if (typee>0 || !Options.EnableReduireUnit)
	    m.push (addCommas(tot));
           else 
            m.push (UniteKMG(tot));
         }
        m.push ('</td>');
      }
      for (i=0; i<row.length; i++){
        m.push ('<TD');
        m.push (style);
        m.push ('>');
        if (typee>0 || !Options.EnableReduireUnit) 
         m.push (addCommas(row[i]));
        else 
         m.push (UniteKMG(row[i]));
        m.push ('</td>');
      }
      if (Options.EnableFormation && typee>0) {
       m.push ('<td>'+addCommas(UniteFormation(typee))+'</td>');    
      }
      if (Options.EnableFormation && name=='Form') {
         if (!Options.EnableReduireUnit)
          m.push("<td>&nbsp;</td><td>" + addCommas(totalentre) + "</td>");
         else
          m.push("<td>&nbsp;</td><td>" + UniteKMG(totalentre) + "</td>");
      }
      m.push ('</tr>');
      return m.join('');
    }

 
    try {
      if (Options.includeMarching)
        march = getMarchInfo ();
  
      dt = new Date ();
      dt.setTime (Seed.player.datejoinUnixTime * 1000);
      
      str = '<DIV class=boStat style="margin-top:4px; margin-bottom:5px; "><TABLE cellspacing=0 class=ptTab cellpadding=0 width=98% align=center>\
        <TR align=left><TD><input type=button value="?" id=boaideresume class=boAide> ' + unsafeWindow.domainName +'</td><TD><SPAN class=boStatLight>Entr&eacute;e le :</span> '+ dt.toLocaleDateString() +'</td>\
        <TD><SPAN class=boStatLight>Alliance : </span> ' + getMyAlliance()[1] +'</td>\
        <TD><SPAN class=boStatLight>'+unsafeWindow.g_js_strings.commonstr.might+' : </span> ' + addCommas(Seed.player.might) +'</td>\
        <TD><SPAN class=boStatLight>'+unsafeWindow.g_js_strings.commonstr.glory+' : </span> ' + addCommas(Seed.player.glory) +' (' + addCommas(Seed.player.maxGlory) +')</td>\
        </tr></table></div><span id="debugtest"></span>';
     
      str += "<DIV id=overMainDiv style='font-size:10px;padding:5px'><TABLE class=ptTabOverview cellpadding=0 cellspacing=0><TR  align=center><TD width=45 align=center></td><TD width=88 style='background: #ffc; font-size:150%' align=center><SPAN class=oohfancy>Totaux</SPAN></td>";
      for(i=0; i<Cities.numCities; i++) {
         cityID = 'city'+ Cities.cities[i].id;
         Gate = parseInt(Seed.citystats[cityID].gate);
	 if(Gate == 0) var couleurr="#77EE77";
         if(Gate != 0) var couleurr="#EE7777";
         
         str += "<TD width=80 style='background-color:"+couleurr+"'><SPAN class=oohfancy>"+ Cities.cities[i].name.substring(0,10) +"</SPAN><BR><a href='javascript:void(0)' onclick='cm.utils.CoordinateLinkController.onClick(event)' class='coordinateLink'>("+Cities.cities[i].x +","+ Cities.cities[i].y+")</a><BR>"+ unsafeWindow.provincenames['p'+ Cities.cities[i].provId] +"</td>";
       
      }

      if (Options.includeMarching)
        str += '<TD width=81><B>March.</b></td>';
      if (Options.EnableFormation)  
       str += "<TD width=81><B>Form.</b></td>"; 
       
      str += "<td></td></tr>";
      str += "<tr><td><DIV id=pbSwfPlayer></div></td><td></td>";
      
      for (var cityId in Cities.byID)
      		str += '<TD><INPUT type=submit id=BOtabut_'+ cityId +' value=""></td>';
      str += '</tr>';
      
      rows = [];
      rowsnm = [];  
      rows[0] = [];
     // Ressources
     if (Options.showRes) {
      for(i=0; i<Cities.numCities; i++) {
        cityID = 'city'+ Cities.cities[i].id;
        rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
      }
      for (r=1; r<6; r++){
        rows[r] = [];
        for(i=0; i<Cities.numCities; i++) {
          cityID = 'city'+ Cities.cities[i].id;
          if (r==5)
           rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
          else
           rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
          
        }
       
      }
  
      if (Options.includeMarching){
        for (var i=0; i<6; i++)
          rows[i][Cities.numCities] = march.resources[i];
      }
      str += _row ('<img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_30.png>', rows[0], false, 0);
      str += _row ('<img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png>', rows[1], false, 0);
      str += _row ('<img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png>', rows[2], false, 0);
      str += _row ('<img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png>', rows[3], false, 0);
      str += _row ('<img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png>', rows[4], false, 0);
      str += _row ('<img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png>', rows[5], false, 0);
      
      if (Options.showProduction) {
       
          str += '<TR><TD><BR></td></tr>';
         
          row = [];
            for(i=0; i<Cities.numCities; i++) {
                        var rp = getResourceProduction (Cities.cities[i].id);
                        row[i] = rp[1];
            }
            str += _row ('<img height=18 title="Production de nourriture a l\'heure" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png>', row, false, 0);
          row = [];
                  for(i=0; i<Cities.numCities; i++) {
                              var rp = getResourceProduction (Cities.cities[i].id);
                              row[i] = rp[2];
                  }
                  str += _row ('<img height=18 title="Production de bois a l\'heure" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png>', row, false, 0);
                  
       row = [];
            for(i=0; i<Cities.numCities; i++) {
                        var rp = getResourceProduction (Cities.cities[i].id);
                        row[i] = rp[3];
            }
            str += _row ('<img height=18 title="Production de pierre a l\'heure" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png>', row, false, 0);
            
       row = [];
            for(i=0; i<Cities.numCities; i++) {
                        var rp = getResourceProduction (Cities.cities[i].id);
                        row[i] = rp[4];
            }
        str += _row ('<img height=18 title="Production de minerais a l\'heure" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png>', row, false, 0);
            
      }
      
      
     }
      
        
            var now = unixTime();
            str += '<TR><TD style="font-size:6px"><BR></font></td></tr>';
            str +='<tr style="background: #fff" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/131.jpg title="Batiment"></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
             var totTime = 0;
             if (Seed.queue_con["city" + Cities.cities[i].id].length > 0) {
              var q=Seed.queue_con["city" + Cities.cities[i].id][0];
              var totTime = 0;
              totTime = q[4] - now;
              if (totTime < 0)
                totTime = 0;
              if (totTime < 3600)
                affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
              else
                affuichage = timestr(totTime);
              str +="<td>"+ affuichage + "</td>";  
             } else {
             str +="<td>0s</td>";
             }
            }    
            str +="</tr>"; 
            //
            str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1.jpg title="Technologie"></b></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
             var totTime = 0;
             if (Seed.queue_tch["city" + Cities.cities[i].id].length > 0) {
              var q=Seed.queue_tch["city" + Cities.cities[i].id][0];
              var totTime = 0;
              totTime = q[3] - now;
              if (totTime < 0)
                totTime = 0;
              if (totTime < 3600)
                affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
              else
                affuichage = timestr(totTime);
              
              str +="<td>"+ affuichage + "</td>";  
       
             } else {
             str +="<td>0s</td>";
             }
            }    
             str +="</tr>"; 
      // crafting
          str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/3.jpg title="Crafting"></b></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
             var totTime = 0;
             if (Seed.queue_craft["city" + Cities.cities[i].id].length > 0) {
              var q=Seed.queue_craft["city" + Cities.cities[i].id][0];
              var totTime = 0;
              totTime = q.craftingEtaUnixTime - now;
              if (totTime < 0)
                totTime = 0;
              if (getCityBuilding(Cities.cities[i].id,20).count>0 && totTime == 0)
                affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
              else
                affuichage = timestr(totTime);
              
              str +="<td><span onclick='BOCrafting("+Cities.cities[i].id+");'>"+ affuichage + "</span></td>";  
       
             } else {
             affuichage = timestr(totTime);
             if (getCityBuilding(Cities.cities[i].id,20).count>0)
                affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                
             str +="<td><span onclick='BOCrafting("+Cities.cities[i].id+");'>"+affuichage+"</span></td>";
             }
            }    
             str +="</tr>";    
      // Population
      
      if (Options.showPop) {
       str += '<TR><TD style="font-size:6px"><BR></td></tr>';
       
              for (r=0; r<7; r++){
                rowsnm[r] = [];
              }
              for(i=0; i<Cities.numCities; i++) {
                cityID = 'city'+ Cities.cities[i].id;
                rowsnm[0][i] = parseIntNan(Seed.citystats[cityID]["pop"][1]); 
                rowsnm[1][i] = parseIntNan(Seed.citystats[cityID]["pop"][0]); 
                rowsnm[2][i] = parseIntNan(Seed.citystats[cityID]["pop"][3]);  
                rowsnm[5][i] = parseIntNan(Seed.citystats[cityID]["pop"][2]); 
                if (rowsnm[5][i] < 100)
		                  rowsnm[5][i] = '<SPAN class=boldRed>' + rowsnm[5][i] + '</SPAN>';
                rowsnm[3][i] = rowsnm[0][i] * rowsnm[5][i] / 100 - rowsnm[2][i];
                rowsnm[4][i] = rowsnm[1][i] - rowsnm[2][i];                     
                rowsnm[6][i] = parseIntNan(Seed.citystats[cityID]["gold"][1]);    
                if (rowsnm[6][i] > 0)
                  rowsnm[6][i] = '<SPAN class=boldRed>' + rowsnm[6][i] + '</SPAN>';
              }
      
              rownum = 0;
              str += _row ('<span class=pdxCapShadowSG>Pop Max</span>',  rowsnm[0]);
              str += _row ('<span class=pdxCapShadowSG>Pop Act.</span>',  rowsnm[1]);
              str += _row ('<span class=pdxCapShadowSG>Travail</span>',  rowsnm[2]);
              str += _row ('<span class=pdxCapShadowSG>Inactive</span>', rowsnm[3]);
              str += _row ('<span class=pdxCapShadowSG>Dispo</span>', rowsnm[4]);
              str += _row ('<span class=pdxCapShadowSG><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/happiness.png title="Bonheur"></span>',  rowsnm[5], true);
        str += _row ('<span class=pdxCapShadowSG><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/taxes.png title="Taux de taxe"></span>', rowsnm[6], true);
      }
      
  str += '<TR><TD style="font-size:6px"><BR></td></tr>';
            row = [];
            var totalbouffe = 0;
            for(i=0; i<Cities.numCities; i++) {
              var rp = getResourceProduction (Cities.cities[i].id);
              var usage = parseIntNan(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
              row[i] = rp[1] - usage;
            }
            str += _row ('Prod', row, false,  0);
            
            for(i=0; i<Cities.numCities; i++) {
              if (row[i] >= 0)
                row[i] = '----';
              else {
                var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-row[i]) * 3600;
                if (timeLeft > 86313600)
                  row[i] = '----';
                else {
                  if (Options.enableFoodWarn && timeLeft<(Options.foodWarnHours*3600))
                    row[i] = '<SPAN class=whiteOnRed><blink>'+ timestrShort(timeLeft) +'</blink></span>';
                  else
                    row[i] = timestrShort(timeLeft);
                }
              }
            }    
      str += _row ('Aut.', row, true, 0);
           
      // Troupes
      if (Options.showTroops) {
      
      str += '<TR><TD style="font-size:6px"><BR></td></tr>';
      for (r=1; r<13; r++){
        rows[r] = [];
        for(i=0; i<Cities.numCities; i++) {
          cityID = 'city'+ Cities.cities[i].id;
          rows[r][i] = parseInt(Seed.units[cityID]['unt'+r]);
        }
      }
      if (Options.includeMarching){
        for (var i=0; i<13; i++)
          rows[i][Cities.numCities] = march.marchUnits[i];
      }
      rownum = 0;
      this.totalentre = 0;
      for (r=1; r<13; r++){
       str += _row ('<img height=18 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg>', rows[r],false, r);
      }
      
      }
      
      var row = [];
            for(i=0; i<Cities.numCities; i++) {
              var totTime = 0;
              var q = Seed.queue_unt['city'+Cities.cities[i].id]; 
              if (q!=null && q.length>0)
                totTime = q[q.length-1][3] - now;
              if (totTime < 0)
                totTime = 0;
              if (totTime < 86400)
                row[i] = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
              else
                row[i] = timestr(totTime);
            }
      str += _row ('Form', row, true, 0);
      
           // Defenses du remparts
            if (Options.showDefense) {
             str += '<TR><TD style="font-size:6px"><BR></td></tr>';
             owsnm = [];
                     for (r=0; r<5; r++){
                       rowsnm[r] = [];
                     }
                     for(i=0; i<Cities.numCities; i++) {
                       var wall = {};
                       getWallInfo (Cities.cities[i].id, wall);
                       rowsnm[0][i] = parseInt(wall.Crossbows);
                       rowsnm[1][i] = parseInt(wall.Trebuchet);
                       rowsnm[2][i] = parseInt(wall.Caltrops);
                       if (isNaN(parseInt(wall.SpikedBarrier))) // KoC bug if wall lvl 0
                         rowsnm[3][i] = 0;
                       else
                       rowsnm[3][i] = parseInt(wall.SpikedBarrier);
                       rowsnm[4][i] = parseInt(wall.Trap);
                     }
                     if (Options.defBau){
                       var q = Seed.queue_unt;
                       for(i=0; i<Cities.numCities; i++) {
                         var q = Seed.queue_fort['city'+Cities.cities[i].id];
                         if (q && q.length>0){
                           for (qi=0; qi<q.length; qi++) {
                             if (q[qi][0]==53)
                               rowsnm[0][i] += parseInt(q[qi][1]);
                             if (q[qi][0]==55)
                               rowsnm[1][i] += parseInt(q[qi][1]);
                             if (q[qi][0]==60)
                               rowsnm[4][i] += parseInt(q[qi][1]);
                             if (q[qi][0]==61)
                               rowsnm[2][i] += parseInt(q[qi][1]);
                             if (q[qi][0]==62)
                               rowsnm[3][i] += parseInt(q[qi][1]);
                           }
                         }
                       }
                     }
             
                     rownum = 0;
                     str += _row ('<span class=pdxCapShadowSG><img height=18 title="'+unsafeWindow.fortcost.frt53[0]+'" src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_53_30.jpg"></span>',  rowsnm[0]);
                     str += _row ('<span class=pdxCapShadowSG><img height=18 title="'+unsafeWindow.fortcost.frt55[0]+'" src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_55_30.jpg"></span>',  rowsnm[1]);
                     str += _row ('<span class=pdxCapShadowSG><img height=18 title="'+unsafeWindow.fortcost.frt60[0]+'" src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_60_30.jpg"></span>',  rowsnm[4]);
                     str += _row ('<span class=pdxCapShadowSG><img height=18 title="'+unsafeWindow.fortcost.frt61[0]+'" src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_61_30.jpg"></span>', rowsnm[2]);
                     str += _row ('<span class=pdxCapShadowSG><img height=18 title="'+unsafeWindow.fortcost.frt62[0]+'" src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_62_30.jpg"></span>',  rowsnm[3]);
      }
      
     
      var row = [];
      for(i=0; i<Cities.numCities; i++) {
        var wall = {};
        getWallInfo (Cities.cities[i].id, wall);
        var totTime = 0;
        var q = Seed.queue_fort['city'+Cities.cities[i].id]; 
        if (q!=null && q.length>0)
          totTime = q[q.length-1][3] - now;
        if (totTime < 0)
          totTime = 0;
        if (totTime<1 && (wall.wallSpaceUsed < wall.wallSpace-4 || wall.fieldSpaceUsed < wall.fieldSpace-4))
          row[i] = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
        else
          row[i] = timestr(totTime);
      } 
      
      
      str += _row ('D&eacute;f', row, true, 0);
      
      str += '<TR><TD style="font-size:6px"><BR></td></tr>';
      
      // Nombre de marches
      row = [];
      for(i=0; i<Cities.numCities; i++) {
        var cityId = 'city'+ Cities.cities[i].id;
        var slots = 0;
        for (var k in Seed.queue_atkp[cityId]){   
         march = Seed.queue_atkp[cityId][k];
         if (typeof (march) == 'object'){
           slots++;
         }
        }
        var niveauPointRall=parseInt(getCityBuilding (Cities.cities[i].id, 12).maxLevel); // 12=Point de ralliement
        if (niveauPointRall==12) niveauPointRall=11;  // fix : Send eleven armies at a time for level 12
        row[i] = '<SPAN><B>'+ slots +'/'+ niveauPointRall +'</b></span>';
      }
      str += _row ('March', row, true, 0);    
      
      // Terres sauvages
      row = [];
      for(i=0; i<Cities.numCities; i++) {
        var totWilds = 0;
        dat = Seed.wilderness['city'+ Cities.cities[i].id];
        if (dat!=null && matTypeof(dat)=='object')
          for (k in dat)
            ++totWilds;
        var nivcastle = parseInt(Seed.buildings['city'+ Cities.cities[i].id].pos0[1]);
        var castle = nivcastle;
        if (nivcastle==11) castle=12; 
        if (nivcastle==12) castle=14; 
        if (totWilds < castle)
        {
         row[i] = '<SPAN class=boldRed><B>'+ totWilds +'/'+ castle +'</b></span>';
        }else{
          
          row[i] = totWilds +'/'+ castle;
        }
      }
      str += _row ('TS', row, true, 0);
      row = [];
      var did = {}; 
      for(i=0; i<Cities.numCities; i++) {
        totKnights = 0;
        dat = Seed.knights['city'+ Cities.cities[i].id];
        for (k in dat)
          ++totKnights;
         
        var Knidispo = 0;
        var niveauPointRall=parseInt(getCityBuilding (Cities.cities[i].id, 12).maxLevel);
        if (niveauPointRall==12) niveauPointRall=11;  // fix : Send eleven armies at a time for level 12
        for (var z=0; z<knightRoles.length; z++){
	        var leader = Seed.leaders['city'+Cities.cities[i].id][knightRoles[z][1]+'KnightId'];
	        if (leader == 0) {
	                
	        }else{
	         did['knt'+leader] = true;
	        }
         }
         for (k in Seed.knights['city'+Cities.cities[i].id]){
	         if (!did[k])
	           Knidispo++;    
         }
         if (Knidispo<niveauPointRall) {
          row[i] = '<b>' + totKnights + '</b> - <span title="Chevalier dispo / Point de ralliement"><SPAN class=boldRed><B>'+Knidispo+'/' + niveauPointRall +'</span></span>';
         }else {
          row[i] = '<b>' + totKnights + '</b> - <span title="Chevalier dispo / Point de ralliement">'+Knidispo+'/' + niveauPointRall +'</span>';
	 }        
         
      }
      str += _row ('Chev', row, true, 0);        
      str += "</table>";
      t.BOResumeDIV.innerHTML = str +'</div>';
      
      function addListener (but, i){
                  but.addEventListener ('click', function (){t.butToggleDefMode(i)}, false);
      }
      for (var cityId in Cities.byID){
        	  var but = document.getElementById ('BOtabut_'+ cityId);
        	  addListener (but, cityId);
        	  t.defMode[cityId] =  parseInt(Seed.citystats["city" + cityId].gate);
        	  t.displayDefMode (cityId);
      }
   
       ById('boaideresume').addEventListener('click', function(){
	       	 window.open(sitesupport+"?page=aide_resume");
    	} , false);
    } catch (e){
      t.BOResumeDIV.innerHTML = '<PRE>'+ e.name +' : '+ e.message +'</pre>';
    }   
    t.displayTimer = setTimeout (t.setContent, 3000);
  },
  butToggleDefMode : function (cityId){
      var t = Tabs.Overview;
      var mode = 1;
      if (Seed.citystats["city" + cityId].gate != 0)
        mode = 0;
      t.ajaxSetDefMode (cityId, mode, function (newMode){
          t.defMode[cityId] = newMode;
          t.displayDefMode (cityId);
        });
    },
        
    displayDefMode : function (cityId){
      var t = Tabs.Overview;
      var but = ById('BOtabut_'+ cityId);
      if (t.defMode[cityId]){
        but.className = 'BODefButOn';
        but.value = 'Def = ON';  
      } else {
        but.className = 'BODefButOff';
        but.value = 'Def = OFF';  
      }  
  },
  ajaxSetDefMode : function (cityId, state, notify){
  		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  		params.cid = cityId;
  		params.state = state;
  		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/gate.php" + unsafeWindow.g_ajaxsuffix, {
  			method: "post",
  			parameters: params,
  			onSuccess: function (rslt) {
  				if (rslt.ok) {
  					Seed.citystats["city" + cityId].gate = state;
  					notify (state);
  				}
  			},
  			onFailure: function () {
  			}
  		})
  },
};

/************** Rapports *******************/
Tabs.Rpt = {
	tabOrder:		2,
	tabLabel:		uW.g_js_strings.commonstr.reports,
	cont:			null,
	state:			null,
	minPages:		parseInt(Options.arPageFrom),
	maxPages:		parseInt(Options.arPageTo),
	data:			[],
	dataDF:	[],dataAT:	[],
	report:			[],
	reportDF:		[],
	reportAT:		[],
	totalPages:	parseInt(Options.arPageTo),
	what:			'',
	whatNot:		'',
	content:		'',

  show : function () {

    var t = Tabs.Rpt;
    if (Options.RptAuto) t.handleRptSearch();
  },
	hide : function (){
  	},

	init : function (div) {
		var t = Tabs.Rpt;
		t.cont = div;
		unsafeWindow.getmsg = t.getMailBody;
		unsafeWindow.DelMail = t.DeleteMail;
		unsafeWindow.getReport = t.getReportBody;
		unsafeWindow.DelReport = t.DeleteReport;
	        var tc = '<DIV class=boStat>'+uW.g_js_strings.commonstr.reports.toUpperCase() +' '+uW.g_js_strings.commonstr.alliance.toUpperCase() +'-'+uW.g_js_strings.commonstr.player.toUpperCase() +' - '+uW.g_js_strings.commonstr.message.toUpperCase() +' - <input type=button value="?" id=boaiderapport class=boAide></DIV><DIV class=ptentry><TABLE><TR align=center valign=center>';
		tc += '<TD class=xtab align=right>Type :&nbsp;<SELECT id="idRptType">';
		tc += '<OPTION value="alliance" ' + (Options.rptType=='alliance'?'SELECTED':'') + '>'+uW.g_js_strings.commonstr.reports+' '+uW.g_js_strings.commonstr.alliance+'</OPTION>';
		tc += '<OPTION value="player" ' + (Options.rptType=='player'?'SELECTED':'') + '>'+uW.g_js_strings.commonstr.reports+' '+uW.g_js_strings.commonstr.player+'</OPTION>';
		tc += '<OPTION value="inbox" ' + (Options.rptType=='inbox'?'SELECTED':'') + '>'+uW.g_js_strings.commonstr.inbox+'</OPTION>';
		tc += '<OPTION value="outbox" ' + (Options.rptType=='outbox'?'SELECTED':'') + '>'+uW.g_js_strings.commonstr.outbox+'</OPTION></SELECT>';
		tc += '<BR /><INPUT id=idRptSearch type=submit value="Ok" />&nbsp;Auto : <input type=checkbox id="idRptAuto" ' +(Options.RptAuto?'CHECKED':'')+'> Pages :&nbsp;<INPUT id="idRptPageFrom" size=1 value="' + Options.arPageFrom + '">&#8211;<INPUT id="idRptPageTo" size=1 value="' + Options.arPageTo + '"></TD>';
		tc += '<TD class=xtab align=right>'+uW.g_js_strings.commonstr.attacker+' :&nbsp;<SELECT id="idRptAttacker">'; // Options.arPageFrom - Options.arPageTo
		tc += '<OPTION value="Them" ' + (Options.arAttacker=='Them'?'SELECTED':'') + '>Eux</OPTION>';
		tc += '<OPTION value="Us" ' + (Options.arAttacker=='Us'?'SELECTED':'') + '>Nous</OPTION>';
		tc += '<OPTION value="Both" ' + (Options.arAttacker=='Both'?'SELECTED':'') + '>Les deux</OPTION></SELECT>';
		tc += '<BR />'+uW.g_js_strings.commonstr.target+' :&nbsp;<SELECT id="idRptTarget">';
		tc += '<OPTION value="Them" ' + (Options.arTarget=='Them'?'SELECTED':'') + '>Eux</OPTION>';
		tc += '<OPTION value="Us" ' + (Options.arTarget=='Us'?'SELECTED':'') + '>Nous</OPTION>';
		tc += '<OPTION value="Both" ' + (Options.arTarget=='Both'?'SELECTED':'') + '>Les deux</OPTION></SELECT></TD>';
		tc += '<TD class=xtab align=right>Contient:&nbsp;<INPUT id=idRptWhat type=text size=11 maxlength=50 value=""><BR />';
		tc += 'Different :&nbsp;<INPUT id=idRptWhatNot type=text size=11 maxlength=50 value=""></TD>';
		tc += '<TD class=xtab align=left><INPUT id=idRptAttack type=checkbox '+(Options.arAttack?'CHECKED':'')+' />&nbsp;'+uW.g_js_strings.commonstr.atk+'<BR />';
		tc += '<INPUT id=idRptScout type=checkbox '+(Options.arScout?'CHECKED':'')+' />&nbsp;'+uW.g_js_strings.commonstr.scouting+'</TD>';
		tc += '<TD class=xtab align=left><INPUT id=idRptReinforce type=checkbox '+(Options.arReinforce?'CHECKED':'')+' />&nbsp;'+uW.g_js_strings.commonstr.reinforce+'<BR />';
		tc += '<INPUT id=idRptTransport type=checkbox '+(Options.arTransport?'CHECKED':'')+' />&nbsp;'+uW.g_js_strings.commonstr.transporting+'</TD>';
		tc += '<TD class=xtab align=left><select id=idRptFiltre1><option value="">--</option><option value="0">TS</option><option value=54>FS</option></select><br>SYNTH : <input type=checkbox id=BOSyntheseAttack></TD></TR></TABLE></DIV>';
		tc += '<DIV class=boStat><TABLE width=100% cellspacing=0><TR><TD class=xtab align=left width=125><DIV id=idRptSearched></DIV></TD></TD>';
		tc += '<TD class=xtab><TD class=xtab align=center><SPAN style="white-space:normal" id=idRptStatus>&nbsp;</span></TD></TD>';
		tc += '<TD class=xtab><TD class=xtab align=right width=125><DIV id=idRptFound></DIV></TD></TR></TABLE></DIV>';
		tc += '<DIV id="idBoRptResultsDiv" style="height:' + (Options.HauteurBoite-140) +'px; max-height:' + (Options.HauteurBoite-140) +'px; overflow-x:auto; overflow-y:auto; white-space:nowrap;"></DIV>';
		
		t.cont.innerHTML = tc;
		
		 ById('boaiderapport').addEventListener('click', function(){
		             	 window.open(sitesupport+"?page=aide_rapport");
		      	} , false);
    	
		ById('idRptType').addEventListener ('change', t.handleRptType, false);
		ById('idRptPageFrom').addEventListener ('change', t.handleRptPages, false);
		ById('idRptPageTo').addEventListener ('change', t.handleRptPages, false);
		ById('idRptAttacker').addEventListener ('change', t.handleRptAttacker, false);
		ById('idRptTarget').addEventListener ('change', t.handleRptTarget, false);
		ById('idRptWhat').addEventListener ('keyup', t.handleRptWhat, false);
		ById('idRptWhatNot').addEventListener ('keyup', t.handleRptWhatNot, false);
		ById('idRptSearch').addEventListener ('click', t.handleRptSearch, false);
		ById('idRptFiltre1').addEventListener ('change', t.handleRptWhat, false);
	
		t.togOpt ('idRptAttack', 'arAttack');
		t.togOpt ('idRptScout', 'arScout');
		t.togOpt ('idRptReinforce', 'arReinforce');
		t.togOpt ('idRptTransport', 'arTransport');
		t.togOpt ('idRptAuto','RptAuto');
		
	},
	DeleteMail: function(rptid, type) {
   var t = Tabs.Rpt;
   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
   params.requestType="ACTION_ON_MESSAGES";
   params.selectedAction="delete";
   params.boxType=ById('idRptType').value;
   params.selectedMessageIds=rptid;

   new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
         method: "post",
         parameters: params,
         onSuccess: function (rslt) {
           if (rslt.ok) {
           
           t.handleRptSearch();
           
           }
           if (notify)
             notify (rslt.errorMsg);
         },
         onFailure: function () {
           if (notify)
             notify ('AJAX ERROR');
         },
       });
  },
  
  DeleteReport: function(rptid, isUnread) {
   var t = Tabs.Rpt;
     
   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
   params.s0rids = rptid;
   params.s1rids = '';
   params.cityrids = '';
   
   new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
         method: "post",
         parameters: params,
         onSuccess: function (rslt) {
           if (rslt.ok) {
           
           if (isUnread){
             unsafeWindow.seed.newReportCount = parseInt(unsafeWindow.seed.newReportCount) - 1;
             unsafeWindow.messages_notify_bug()
           } 
           //t.handleRptSearch();
           //t.DisplayRpt();
           }
    
         },
         onFailure: function () {
             t.handleRptSearch();
         },
       });
  },
	togOpt: function (checkboxId, optionName){
		var t = Tabs.Rpt;
		var checkbox = ById(checkboxId);
		checkbox.addEventListener ('change', eventHandler, false);
		function eventHandler (){
			Options[optionName] = this.checked;
			saveOptions();
			if (t.data.length > 0)
				if (Options.rptType == 'alliance' || Options.rptType == 'player')
					t.DisplayRpt();
				else
					t.DisplayMail();
		}
	},

	handleRptType: function(){
		var t = Tabs.Rpt;
		Options.rptType = ById("idRptType").value;
		saveOptions();
		ById("idRptSearched").innerHTML = '';
		ById("idRptStatus").innerHTML = '&nbsp;';
		ById("idRptFound").innerHTML = '';
		ById("idBoRptResultsDiv").innerHTML = '';
	},

	handleRptPages: function(){
		var t = Tabs.Rpt;
		t.minPages=parseInt(ById("idRptPageFrom").value);
		t.maxPages=parseInt(ById("idRptPageTo").value);
		if (t.maxPages < t.minPages) {
			t.maxPages = t.minPages;
			ById("idRptPageTo").value = t.maxPages;
		}
		Options.arPageFrom = t.minPages;
		Options.arPageTo = t.maxPages;
		saveOptions();
		t.totalPages=t.maxPages;
	},

	handleRptAttacker: function(){
		var t = Tabs.Rpt;
		Options.arAttacker = ById("idRptAttacker").value;
		saveOptions();
		if ((Options.rptType == 'alliance' || Options.rptType == 'player') && t.data.length > 0)
			t.DisplayRpt();
	},

	handleRptTarget: function(){
		var t = Tabs.Rpt;
		Options.arTarget = ById("idRptTarget").value;
		saveOptions();
		if ((Options.rptType == 'alliance' || Options.rptType == 'player') && t.data.length > 0)
			t.DisplayRpt();
	},

	handleRptWhat: function(){
		var t = Tabs.Rpt;
		t.what = ById("idRptWhat").value;
		if (t.data.length > 0)
			if (Options.rptType == 'alliance' || Options.rptType == 'player')
				t.DisplayRpt();
			else
				t.DisplayMail();
	},

	handleRptWhatNot: function(){
		var t = Tabs.Rpt;
		t.whatNot = ById("idRptWhatNot").value;
		if (t.data.length > 0)
			if (Options.rptType == 'alliance' || Options.rptType == 'player')
				t.DisplayRpt();
			else
				t.DisplayMail();
	},

	handleRptSearch: function(){
		var t = Tabs.Rpt;
		if (t.searchRunning){
			t.searchRunning = false;
			t.stopSearch (uW.g_js_strings.commonstr.cancelled.toUpperCase());
			return;
		}
		t.handleRptPages();
		document.getElementById ('idRptSearch').value = 'Stop';
		ById('idRptStatus').innerHTML = uW.g_js_strings.commonstr.research+' page ' + t.minPages + ' / ' + t.maxPages;
		t.searchRunning = true;
		t.data=[];
		t.report = [];
		t.dataDF=[];
		t.dataAT=[];
		t.reportAT=[];
		t.reportDF = [];
		if (Options.rptType == 'alliance' || Options.rptType == 'player')
			t.getRpt(t.minPages);
		else
			t.getMail(t.minPages);
	},

	stopSearch: function (msg){
		var t = Tabs.Rpt;
		if (t.searchRunning || msg == uW.g_js_strings.commonstr.cancelled.toUpperCase())
			document.getElementById ('idRptStatus').innerHTML = '<FONT color=#ffaaaa>' + msg + '</FONT>';
		document.getElementById ('idRptSearch').value = 'Ok';
		t.searchRunning = false;
		if (Options.rptType == 'alliance' || Options.rptType == 'player')
			t.DisplayRpt();
		else
			t.DisplayMail();
	},

	getMail: function (pageNum){
		var t = Tabs.Rpt;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.pf=0;
		params.requestType="GET_MESSAGE_HEADERS_FOR_USER_INBOX";
		params.boxType = ById('idRptType').value;
		params.pageNo = pageNum;
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				t.getMailCallback(rslt, pageNum);
			},
			onFailure: function () {
			},
		}, false);
	},

	getMailCallback: function(rslt, page) {
		var t = Tabs.Rpt;
		if (rslt) {
			if (!rslt.ok) {
				ById("idRptStatus").innerHTML = '<FONT color=#ffaaaa>' + rslt.errorMsg + '</FONT>';
				return;
			}
			t.totalPages=parseInt(rslt.noOfPages);
			if (t.totalPages < t.maxPages)
				t.maxPages = t.totalPages;
			if (rslt.message && page) {
				var ml = rslt.message;
				if (rslt.messageCount > 0) {
					var rptkeys = unsafeWindow.Object.keys(ml);
					for (var i = 0; i < rptkeys.length; i++) {
						var rpt = ml[rptkeys[i]];
						rpt.page = page;
						t.data.push(rpt);
					}
				}
			}
			if (parseInt(page)+1 <= t.maxPages && t.searchRunning) {
				ById("idRptStatus").innerHTML = uW.g_js_strings.commonstr.research +' page ' + (parseInt(page)+1) + ' / ' + t.maxPages;
				t.getMail(parseInt(page)+1);
				if (t.data.length > 0)
					t.DisplayMail();
			} else if (page)
				t.stopSearch ('Fini !');
		}
	},

	getRpt: function (pageNum){
		var t = Tabs.Rpt;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.pageNo = pageNum;
		if (Options.rptType == 'alliance')
			params.group = "a";
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt){
				t.getRptCallback (rslt, pageNum);
			},
			onFailure: function (rslt){
				t.getRptCallback (rslt, pageNum);
			},
		}, false);
	},
	getRptCallback: function(rslt, page){
		var t = Tabs.Rpt;
		if (rslt) {
			if (!rslt.ok) {
				ById("idRptStatus").innerHTML = '<FONT color=#ffaaaa>' + rslt.errorMsg + '</FONT>';
				return;
			}
			t.totalPages=parseInt(rslt.totalPages);
			if (t.totalPages < t.maxPages)
				t.maxPages = t.totalPages;
			if (rslt.arReports && page) {
				var ar = rslt.arReports;
				//if (ar.length == 0)
					//t.stopSearch('Page vide trouve depuis la page ' + page + ' - Kabam glitch');
				var rptkeys = unsafeWindow.Object.keys(ar);
				for (var i = 0; i < rptkeys.length; i++) {
					var rpt = ar[rptkeys[i]];
					var reportId = parseInt(rpt.reportId);
					t.report[reportId] = [];
					t.report[reportId].side1Name = rslt.arPlayerNames['p'+rpt.side1PlayerId];
					t.report[reportId].side1AllianceId = parseInt(rpt.side1AllianceId);
					if (rpt.side1AllianceId > 0)
						t.report[reportId].side1AllianceName = rslt.arAllianceNames['a'+rpt.side1AllianceId];
					else
						t.report[reportId].side1AllianceName = '-';
					if (rpt.side1CityId > 0)
						t.report[reportId].side1CityName = rslt.arCityNames['c'+rpt.side1CityId];
					else
						t.report[reportId].side1CityName = '-';
					t.report[reportId].side1XCoord = rpt.side1XCoord;
					t.report[reportId].side1YCoord = rpt.side1YCoord;
					if (parseInt(rpt.side0PlayerId) == 0) { // Kabam
						t.report[reportId].side0Name = 'Ennemi';
						t.report[reportId].side0AllianceName = '';
						t.report[reportId].side0CityName = '';
					} else {
						t.report[reportId].side0Name = rslt.arPlayerNames['p'+rpt.side0PlayerId];
						if (rpt.side0AllianceId > 0)
							t.report[reportId].side0AllianceName = rslt.arAllianceNames['a'+rpt.side0AllianceId];
						else
							t.report[reportId].side0AllianceName = '-';
						if (rpt.side0CityId > 0)
							t.report[reportId].side0CityName = rslt.arCityNames['c'+rpt.side0CityId];
						else
							t.report[reportId].side0CityName = '-';
					}
					t.report[reportId].side0AllianceId = parseInt(rpt.side0AllianceId);
					t.report[reportId].side0XCoord = rpt.side0XCoord;
					t.report[reportId].side0YCoord = rpt.side0YCoord;
					if (parseInt(rpt.side0TileType) == 10)
						t.report[reportId].side0TileTypeText='Prair';
					else if (parseInt(rpt.side0TileType) == 11)
						t.report[reportId].side0TileTypeText='Lac';
					else if (parseInt(rpt.side0TileType) == 20)
						t.report[reportId].side0TileTypeText='Fore';
					else if (parseInt(rpt.side0TileType) == 30)
						t.report[reportId].side0TileTypeText='Coll';
					else if (parseInt(rpt.side0TileType) == 40)
						t.report[reportId].side0TileTypeText='Mont';
					else if (parseInt(rpt.side0TileType) == 50)
						t.report[reportId].side0TileTypeText='Plai';
					else if (parseInt(rpt.side0TileType) == 51 && parseInt(rpt.side0CityId) == 0)
						t.report[reportId].side0TileTypeText='Barb';
					else if (parseInt(rpt.side0TileType) == 54)
						t.report[reportId].side0TileTypeText='F.S.';
					else if (parseInt(rpt.side0CityId) == 0)
						t.report[reportId].side0TileTypeText='Barb';
					else
						t.report[reportId].side0TileTypeText='Vil';
						
						
						
					
					t.report[reportId].side0TileTypeLevel = t.report[reportId].side0TileTypeText + ' ' + rpt.side0TileLevel;
					t.report[reportId].side0TileType = rpt.side0TileType;
					t.report[reportId].side0TileLevel = rpt.side0TileLevel;
					t.report[reportId].page = page;
					t.report[reportId].reportUnixTime = rpt.reportUnixTime;
					if (rpt.side0AllianceId == parseInt(getMyAlliance()[0]))
						t.report[reportId].sideId = 0;
					else if (rpt.side1AllianceId == parseInt(getMyAlliance()[0])) {
						t.report[reportId].sideId = 1;
					} else { 
						if (rpt.side0PlayerId == getMyUserId())
							t.report[reportId].sideId = 0;
						else if (rpt.side1PlayerId == getMyUserId())
							t.report[reportId].sideId = 1;
						else 
							t.report[reportId].sideId = -1;
					}					
					if (!ById("BOSyntheseAttack").checked && parseInt(rpt.side0TileType) == 54 && Options.rptType=='player') {
					    t.FindItemRpt(reportId, t.report[reportId].sideId, t.report[reportId].side0TileLevel);  
				        }
					if (ById("BOSyntheseAttack").checked && (rpt.marchType == 4 || rpt.marchType == 3))
					{
					    t.BOSyntheseAttack(reportId, t.report[reportId].sideId, 0);
					}
					
					if (rpt.marchType == 0)
						t.report[reportId].marchName = 'Desertion';
					else if (rpt.marchType == 1)
						t.report[reportId].marchName = 'Transport';
					else if (rpt.marchType == 2)
						t.report[reportId].marchName = 'Renfort';
					else if (rpt.marchType == 3 || rpt.marchType == 11) {
						if (t.report[reportId].sideId == 0)
							t.report[reportId].marchName = 'Contre-Ecl';
						else
							t.report[reportId].marchName = 'Eclaireur';
					} else if (rpt.marchType == 4) {
						if (t.report[reportId].sideId == 0)
							t.report[reportId].marchName = 'Defense';
						else
							t.report[reportId].marchName = 'Attaque';
					} else if (rpt.marchType == 10 || rpt.marchType == 9) {
					 t.report[reportId].marchName = 'Attaque';
					} else
						t.report[reportId].marchName = '?';
					t.data.push ({
						reportId: reportId,
					});
				}
			}
			if (parseInt(page)+1 <= t.maxPages && t.searchRunning) {
				ById("idRptStatus").innerHTML = uW.g_js_strings.commonstr.research + ' page ' + (parseInt(page)+1) + ' / ' + t.maxPages;
				t.getRpt(parseInt(page)+1);
				if (t.data.length > 0)
					t.DisplayRpt();
			} else if (page) {
				
				if (ById("BOSyntheseAttack").checked) {
				 t.stopSearch ('<a id=BOresumeAT style="color:#ffaaaa" onclick="javascript:void(0);"><u>affichage du resume attaque</u></a>');
				 setTimeout(function() {
								 // ouverture du resume des rapports FS avec Items
								   ById("BOresumeAT").addEventListener ('click', t.AfficheResumeAtk, false);
				  }, 1000);
				} else {
				
				if (Options.rptType=='player') {
				 t.stopSearch ('<a id=BOresumeDF style="color:#ffaaaa" onclick="javascript:void(0);"><u>affichage du resume '+unsafeWindow.g_js_strings.commonstr.darkForest+'</u></a>');
				 setTimeout(function() {
				 // ouverture du resume des rapports FS avec Items
				   ById("BOresumeDF").addEventListener ('click', t.AfficheResume, false);
				  }, 1000);
				 } else {
				  t.stopSearch ('Fini !');
				 }
				}
			}
		}
	},
	AfficheResumeAtk:function() {
	 var t = Tabs.Rpt;
	 var puipui=new Array();
	 var fortmight = {u53: "4",u55: "7",u60: "1",u61: "2",u62: "3",    };
	 for (var ui = 1 ; ui<13; ui++)
		 puipui.push(unsafeWindow.unitmight['unt'+ui]);
	 puipui[52] = fortmight['u53'];
	 puipui[54] = fortmight['u55'];
	 puipui[59] = fortmight['u60'];
	 puipui[60] = fortmight['u61'];
	 puipui[61] = fortmight['u62'];
	 var messageBody="";
	 reportsSearched = t.dataAT.length;
	 reportsFound = 0;
         var tr0=0,tr1=0,tr2=0,tr3=0,tr4=0,tr5=0;
	 if (reportsSearched>0) {
	  messageBody +='<br><table width=98%><thead><th>Joueur<br>Alliance</th><th><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_30.png></th>\
	  <th><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png></th><th><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png></th>\
	  <th><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png></th><th><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png></th>\
	  <th><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png></th></thead><tbody>';
	  t.dataAT.sort(function(a, b){
		var sortA=a.nom,sortB=b.nom;
		if (sortA < sortB) return -1
		if (sortA > sortB) return 1
		return 0 
	  });
	 var datartp = [];
	 var nbrp=0;
	 for (var i=0; i<reportsSearched;i++) {
	  var idrapport=t.dataAT[i].reportId;
	  if ((t.what == '' || (t.dataAT[i].nom.search(t.what, "i") != -1)  || (t.dataAT[i].alliance.search(t.what, "i") != -1))
	      && (t.whatNot == '' || (t.dataAT[i].nom.search(t.whatNot, "i") != -1 && t.dataAT[i].alliance.search(t.whatNot, "i") != -1)))
	  {
	   
	   if (datartp[nbrp]==undefined) { 
	     datartp[nbrp]=[];
	     datartp[nbrp].nom = t.dataAT[i].nom;
	     datartp[nbrp].alliance = t.dataAT[i].alliance;
	     datartp[nbrp].res0=0;
	     datartp[nbrp].res1=0;
	     datartp[nbrp].res2=0;
	     datartp[nbrp].res3=0;
	     datartp[nbrp].res4=0;
	     datartp[nbrp].res5=0;
	     for (var z=1;z<64;z++) {
	      datartp[nbrp]['s1unit'+z] =0;
	      datartp[nbrp]['s0unit'+z] =0;
	     }
	   }  
	   if(datartp[nbrp].nom==t.dataAT[i].nom && datartp[nbrp].alliance==t.dataAT[i].alliance) {
	     datartp[nbrp].res0 += parseIntNan(t.reportAT[idrapport].res0);
	     datartp[nbrp].res1 += parseIntNan(t.reportAT[idrapport].res1);
	     datartp[nbrp].res2 += parseIntNan(t.reportAT[idrapport].res2);
	     datartp[nbrp].res3 += parseIntNan(t.reportAT[idrapport].res3);
	     datartp[nbrp].res4 += parseIntNan(t.reportAT[idrapport].res4);
	     datartp[nbrp].res5 += parseIntNan(t.reportAT[idrapport].res5);
	       for (var z=1;z<64;z++) {
	        datartp[nbrp]['s1unit'+z] += parseIntNan(t.reportAT[idrapport]['s1unit'+z]);
	        datartp[nbrp]['s0unit'+z] += parseIntNan(t.reportAT[idrapport]['s0unit'+z]);
	      }
	   } else {
	     nbrp++;
	     datartp[nbrp]=[];
	     datartp[nbrp].nom = t.dataAT[i].nom;
	     datartp[nbrp].alliance = t.dataAT[i].alliance;
	     datartp[nbrp].res0=0;
	     datartp[nbrp].res1=0;
	     datartp[nbrp].res2=0;
	     datartp[nbrp].res3=0;
	     datartp[nbrp].res4=0;
	     datartp[nbrp].res5=0;
	     datartp[nbrp].res0 += parseIntNan(t.reportAT[idrapport].res0);
	     datartp[nbrp].res1 += parseIntNan(t.reportAT[idrapport].res1);
	     datartp[nbrp].res2 += parseIntNan(t.reportAT[idrapport].res2);
	     datartp[nbrp].res3 += parseIntNan(t.reportAT[idrapport].res3);
	     datartp[nbrp].res4 += parseIntNan(t.reportAT[idrapport].res4);
	     datartp[nbrp].res5 += parseIntNan(t.reportAT[idrapport].res5);
	     for (var z=1;z<64;z++) {
	     	      datartp[nbrp]['s1unit'+z] =0;
	     	      datartp[nbrp]['s0unit'+z] =0;
	     	      datartp[nbrp]['s1unit'+z] += parseIntNan(t.reportAT[idrapport]['s1unit'+z]);
	     	      datartp[nbrp]['s0unit'+z] += parseIntNan(t.reportAT[idrapport]['s0unit'+z]);	     
	     }
	   }
	   }// fin du regrouppement
	  }
	  reportsSearched = datartp.length;
	  var tres=[0,0,0,0,0,0];
	  var perts1=[];var perts0=[];
	  for (var z=1;z<64;z++) { perts1[z]=0;perts0[z]=0; }
	  
	  for (var i=0; i<reportsSearched;i++) {
	   messageBody += '<tr><td>'+datartp[i].nom+'<br>'+datartp[i].alliance+'</td>';
	    for (var res=0;res<6;res++) {
	     messageBody += '</td><td align=right>';
	     var cb=0;
	     if (datartp[i]["res"+res] != undefined) {
	       cb=parseIntNan(datartp[i]["res"+res]);
	       tres[res]+=cb;
	     }
	     messageBody += addCommas(cb);
	    }
	    for (var z=1;z<64;z++) {
	     perts1[z]+=parseIntNan(datartp[i]['s1unit'+z]);
	     perts0[z]+=parseIntNan(datartp[i]['s0unit'+z]);
	    } 
	  }
	  messageBody += '</td></tr><tr><td><b>TOTAUX : </td>';
	  for (var res=0;res<6;res++) messageBody +='<td align=right><b>'+addCommas(tres[res])+'</b></td>';
	  messageBody += "</tr></table>";
	  messageBody += "<br><table><thead><th width=120><b>Nos pertes</b></th>";
	  for (var z=1;z<64;z++) {
	    if (perts1[z]>0) {
	      messageBody +='<th width=6%><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+z+'_30.jpg ';
	      if(z<14)
	        messageBody +='title="'+unsafeWindow.unitcost['unt'+z][0]+'"';
	      messageBody +='></th>';
	    }
	  }
	  messageBody +='<th></th></thead><tr><td>Nombre</td>';
	  for (var z=1;z<64;z++) if (perts1[z]>0) messageBody +='<td align=right>'+ addCommas(perts1[z])+'</td>';
	  messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+'</td>';
	  for (var z=1;z<64;z++) if (perts1[z]>0) messageBody +='<td align=right>'+ addCommas(parseIntNan(perts1[z])*parseIntNan(puipui[z-1]))+'</td>';
	  var to1=0;
	  messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+' total</td>';
	  for (var z=1;z<64;z++) to1+=(parseIntNan(perts1[z])*parseIntNan(puipui[z-1]));
	  messageBody += "<td align=right><b>"+addCommas(to1)+"</b></td></tr><thead><th><b>Leurs pertes</b></th>";
	  for (var z=1;z<64;z++) {
	   if (perts0[z]>0) {
	      messageBody +='<th width=6%><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+z+'_30.jpg ';
	      if(z<14)
	        messageBody +='title="'+unsafeWindow.unitcost['unt'+z][0]+'"';
	      messageBody +='></th>';
	   }
	  }
	  messageBody +='<th></th></thead><tr><td>Nombre</td>';
	  for (var z=1;z<64;z++) if (perts0[z]>0)messageBody +='<td align=right>'+ addCommas(parseIntNan(perts0[z]))+'</td>';
	  messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+'</td>';
	  
	  for (var z=1;z<64;z++) if (perts0[z]>0)messageBody +='<td align=right>'+ addCommas(parseIntNan(perts0[z])*parseIntNan(puipui[z-1]))+'</td>';
	  var to2=0;
	  messageBody +='</tr><tr><td>'+uW.g_js_strings.commonstr.might+' total</td>';
	  for (var z=1;z<64;z++) to2+= (parseIntNan(perts0[z])*parseIntNan(puipui[z-1]));
	  messageBody +="<td align=right><b>"+addCommas(to2)+"</b></td></tr></table><br>";

	  if (to1<to2)
	    messageBody += "<br><b>Diff&eacute;rence de puissance : <font color=#449944>"+addCommas((to2-to1))+"</font><br>";
	  if (to1==to2)
	    messageBody += "<br><b>Aucune perte des deux cot&eacute;s<br>";  
	   if (to1>to2)
	    messageBody += "<br><b>Diff&eacute;rence de puissance : <font color=#994444>"+addCommas((to1-to2))+"</font><br>";  
	    
	 } else {
	  messageBody +="<br><center>Aucun rapport d\'attaque trouv&eacute;<br>";
	 }
	 t.popRapportAT = new CPopup('pbRapportATBody', 0, 0, 770, 500, true, function() {clearTimeout (1000);});
	 t.popRapportAT.centerMe (mainPop.getMainDiv());
	 var m = '<DIV style="max-height:465px; height:465px; overflow-y:scroll">';
	 m+= messageBody + '</div>';
	 t.popRapportAT.getMainDiv().innerHTML = m;
	 t.popRapportAT.getTopDiv().innerHTML = '<DIV align=center><B>R&eacute;sum&eacute; des rapports d\'attaque(s)</B></DIV>';
	 t.popRapportAT.show(true);
	},
	AfficheResume:function() {
	 var t = Tabs.Rpt;
	 var messageBody="";
	 reportsSearched = t.dataDF.length;
	 reportsFound = 0;
	 if (t.dataDF.length>0) {
	messageBody +='<br><center><table width=60%><thead><th>Rapport</th><th>Niveau</th><th colspan=2>Objet trouv&eacute;</th></thead><tbody>';
	for (var i=0; i<reportsSearched;i++) {
	var idrapport=t.dataDF[i].reportId;
	var rpt =  t.reportDF[idrapport];
	messageBody += '<tr><td align=right><a onclick="getReport('+ idrapport+')">'+idrapport+'</A></td><td>'+rpt.lvl+'</td><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/' + rpt.item + '.jpg></td><td>'+unsafeWindow.ksoItems[rpt.item].name+'</td></tr>';
	}
	messageBody += "</tbody></table>";
	} else {
	messageBody +="<br><center>Aucun objet trouv&eacute;<br>";
	}
	
	messageBody +='<br><input type=button value="Supprimer les rapports concernes" id=BODelAllDF></center>';
	
	
	t.popRapportDF = new CPopup('pbRapportDFBody', 0, 0, 500, 400, true, function() {clearTimeout (1000);});
	t.popRapportDF.centerMe (mainPop.getMainDiv());

	var m = '<DIV style="max-height:365px; height:4365px; overflow-y:scroll">';
	m+= messageBody + '</div>';
	t.popRapportDF.getMainDiv().innerHTML = m;
	t.popRapportDF.getTopDiv().innerHTML = '<DIV align=center><B>R&eacute;sum&eacute; des rapports de '+unsafeWindow.g_js_strings.commonstr.darkForest+'</B></DIV>';
	t.popRapportDF.show(true);
	ById('BODelAllDF').addEventListener ('click', t.DeleteRptDF, false);
					
	},
	pagesasup:0,
	DeleteRptDF:function() {
	 var t = Tabs.Rpt;
	 t.pagesasup = 0;
	 t.fetchreport(0, t.checkreports);
	 t.popRapportDF.show(false);
	 t.popRapportDF.destroy();
	 t.popRapportDF = null;
	},
	 fetchreport : function(pageNo, callback){
		var t =  Tabs.Rpt;
		 if (t.pagesasup>=t.maxPages) return;
			var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
			if(pageNo > 1)
				params.pageNo = pageNo;
			new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
				        t.pagesasup++;
					callback(rslt);
				},
					onFailure: function () {
					t.pagesasup++;
					callback();
				},
			});
	    },
		
	    checkreports : function(rslt){
			var t = Tabs.Rpt;
			if(!rslt.ok){
				return;
			}
			if(rslt.arReports.length < 1){
				return;
			}
			var reports = rslt.arReports;
			var totalPages = rslt.totalPages;
			var deletes1 = new Array();
			for(k in reports){
					if(reports[k].side0TileType==54)
						deletes1.push(k.substr(2));
				
			}
			if(deletes1.length > 0 ){
				t.deleteCheckedReports(deletes1);
			} else {
				
				return;
			}
	    },
    	deleteCheckedReports : function(deletes1){
    		var t =  Tabs.Rpt;
    		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    		params.s1rids = deletes1.join(",");
    		params.cityrids = '';
    		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
    			method: "post",
    			parameters: params,
    			onSuccess: function (rslt) {
    				if(rslt.ok){
    					Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length);
    				}
    				t.fetchreport(0, t.checkreports);
    				t.DisplayRpt();
    			},
    			onFailure: function () {
    			},
    		});
    },
    BOSyntheseAttack:function(reportId, sideId, lvl) {
     // synthÃ¨se sur les rapports  d'attaque
     
     
     var t = Tabs.Rpt;
     var rpt = t.report[reportId];
     var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
     	  params.rid=reportId;
	  params.side=sideId;
     if (params.side > -1) {
     	   new AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/fetchReport.php"+unsafeWindow.g_ajaxsuffix, {  method:"post",  parameters:params,
       
     	   onSuccess:function(msg){
     		var rslt = eval("(" + msg.responseText + ")");
     		t.dataAT.push ({reportId: reportId, nom:rpt.side0Name, alliance:rpt.side0AllianceName});
     		t.reportAT[reportId] = [];
     		t.reportAT[reportId].nom = rpt.side0Name;
     		t.reportAT[reportId].alliance = rpt.side0AllianceName;
     		t.reportAT[reportId].res0=0;
     		t.reportAT[reportId].res1=0;
     		t.reportAT[reportId].res2=0;
     		t.reportAT[reportId].res3=0;
     		t.reportAT[reportId].res4=0;
     		t.reportAT[reportId].res5=0;
     		if (rslt.loot) {
     		 if (rslt['loot'][0] !== undefined) t.reportAT[reportId].res0=rslt['loot'][0];
     		 if (rslt['loot'][1] !== undefined) t.reportAT[reportId].res1=rslt['loot'][1];
     		 if (rslt['loot'][2] !== undefined) t.reportAT[reportId].res2=rslt['loot'][2];
     		 if (rslt['loot'][3] !== undefined) t.reportAT[reportId].res3=rslt['loot'][3];
     		 if (rslt['loot'][4] !== undefined) t.reportAT[reportId].res4=rslt['loot'][4];
     		 if (rslt['loot'][6] !== undefined) t.reportAT[reportId].res5=rslt['loot'][6];
     	        }
     	        if (sideId==0) { // les pertes !!!!
     	         for (var zz=0;zz<6;zz++)
     	            t.reportAT[reportId]["res"+zz] = t.reportAT[reportId]["res"+zz] *-1;
     	        }
     	        if (rslt['fght'] != undefined){
     	        	if (rslt['fght']["s1"] != undefined) {
     	        		for (var i=1;i<13;i++) {
					if (rslt['fght']["s1"]['u'+i] != undefined) {
						if (sideId==1) t.reportAT[reportId]['s1unit'+i]=rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1]; // perte 
						else t.reportAT[reportId]['s0unit'+i]=rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1]; // perte 

					}else{
					 	if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
						else t.reportAT[reportId]['s0unit'+i]=0;
					}
				}
				for (var i=53;i<=55;i++) {
					if (rslt['fght']["s1"]['f'+i] != undefined) {
						if (sideId==1) t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];
						else t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];
				
			 		}else{
			 			if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
			 			else t.reportAT[reportId]['s0unit'+i]=0;
					}
			 	}
		 		for (var i=60;i<=63;i++) {
					if (rslt['fght']["s1"]['f'+i] != undefined) {
						if (sideId==1) t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];
						else t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];
				
					}else{
			 			if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
			 			else t.reportAT[reportId]['s0unit'+i]=0;
					}
			 	}	
		 	}
     	         	if (rslt['fght']["s0"] != undefined) {
     	         		for (var i=1;i<13;i++) {
					if (rslt['fght']["s0"]['u'+i] != undefined) {
					  if (sideId==1) {
					   t.reportAT[reportId]['s0unit'+i]=rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1]; // perte
					  }else{
					    t.reportAT[reportId]['s1unit'+i]=rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1]; // perte
					  }
					} else {
					 if (sideId==1) {
					  t.reportAT[reportId]['s0unit'+i]=0;
					 } else {
					   t.reportAT[reportId]['s1unit'+i]=0;
					 }
					}
				}
     	         		for (var i=53;i<=55;i++) {
		 			if (rslt['fght']["s0"]['f'+i] != undefined) {
		 				if (sideId==1) {
		 					t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
		 				} else {
		 					t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
		 				}
		 			}else{
						if (sideId==1) t.reportAT[reportId]['s0unit'+i]=0;
						else t.reportAT[reportId]['s1unit'+i]=0;
					}
			 	}
		 		for (var i=60;i<=63;i++) {
		 			if (rslt['fght']["s0"]['f'+i] != undefined) {
		 				if (sideId==1) {
		 					t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
		 				} else {
		 					t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
		 				}
		 			}else{
			 			if (sideId==1) {
			 					t.reportAT[reportId]['s0unit'+i]=0;
			 				} else {
			 					t.reportAT[reportId]['s1unit'+i]=0;
						}
			 		}	
		 		}
			}
     	        }
     	        
        } });
      }  
    },
    FindItemRpt:function(reportId, sideId, lvl) {
	  var t = Tabs.Rpt;
	  var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
	  params.rid=reportId;
	  params.side=sideId;
	  if (params.side > -1) {
	   new AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/fetchReport.php"+unsafeWindow.g_ajaxsuffix, {  method:"post",  parameters:params,
  
	   onSuccess:function(msg){
		var rslt = eval("(" + msg.responseText + ")");
		if (rslt.loot) {
			if (rslt['loot'][5] !== undefined) {
				var q=unsafeWindow.Object.keys(rslt['loot'][5]);
				if (q.length>0) {
			 			  for(var u=0,y=q.length;u<y;++u){
			 				C=q[u];
			 				if (unsafeWindow.ksoItems[C]!==undefined) {
			 				 t.dataDF.push ({reportId: reportId,});
			 				 t.reportDF[reportId] = [];
			 				 t.reportDF[reportId].lvl = lvl;
			 				 t.reportDF[reportId].item = C;
			 				}
			 			  }
			 	}
			
	          
	                    }
	          
	               }
	        }
            });
          }  
	
	},
	DisplayMail: function (){
		var t = Tabs.Rpt;
		var results = ById("idBoRptResultsDiv");
		if(!t.data.length) {
			results.innerHTML = '<center>Aucun resultat</center>';
			return;
		}
		reportsSearched = t.data.length;
		reportsFound = 0;
		t.content = '';
		for (var i=0; i<reportsSearched;i++) {
			var rpt = t.data[i];
			if ((t.what == '' || (rpt.subject.search(t.what, "i") != -1) || (rpt.displayName.search(t.what, "i") != -1))
				&& (t.whatNot == '' || ((rpt.subject.search(t.whatNot, "i") == -1) && (rpt.displayName.search(t.whatNot, "i") == -1)))) {
				if (rpt.subject == '')
					rpt.subject = '&lt;Sans Sujet&gt;';
				reportsFound++;
				if (reportsFound == 1)
					t.content += '<center><table width=97%><thead><th>P</th><th>Date</th><th>De</th><th>Sujet</th><th>Sup</th></thead><tbody>';
				var stylee="";
				if (rpt.messageRead==0) stylee=' style="background-color:#CCCCCC;"';
				t.content += '<tr><td align=right '+stylee+'>'+rpt.page+'</td><td '+stylee+'>'+rpt.dateSent+'</td><td '+stylee+'>'+rpt.displayName+'</td>';
				t.content += '<td '+stylee+'><A><SPAN onclick="getmsg('+ rpt.messageId +')">' + rpt.subject + '</SPAN></a></td><td><a onclick="DelMail('+ rpt.messageId +');"><img src="http://cdn1.iconfinder.com/data/icons/musthave/16/Remove.png" border=0 title="Supprimer ce message"></a></td></tr>';
			}
		}
		if (reportsFound > 1)
			t.content += '</tbody></table></center>';
		if (reportsFound == 0 && reportsSearched > 0)
			t.content = '<center>Aucun resultat</center>';
		results.innerHTML = t.content;
		ById("idRptSearched").innerHTML = '&nbsp;Resultat : ' + reportsSearched;
		ById("idRptFound").innerHTML = 'Trouve : ' + reportsFound;
	},

	getMailBody: function(ID,dataI){
		var t = Tabs.Rpt;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.messageId=ID;
		params.requestType="GET_MESSAGE_FOR_ID";

		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if (rslt.ok)
					t.displayMailBody(rslt.messageBody, ID);
			},
			onFailure: function () {},
		}, false);
	},

	displayMailBody: function (messageBody, ID) {
		var t = Tabs.Rpt;
		if (t.popMsg == null) {
		  t.popMsg = new CPopup('pbMailBody', 0, 0, 670, 500, true, function() {clearTimeout (1000);});
		  t.popMsg.centerMe (mainPop.getMainDiv());
		}
		messageBody=messageBody.replace(/custom-line-break/g,"<br>");
		var m = '<DIV style="max-height:465px; height:465px; overflow-y:scroll"><br><hr>';
		m+= messageBody + '<hr><a onclick="DelMail('+ ID +');"><img src="http://cdn1.iconfinder.com/data/icons/musthave/16/Remove.png" border=0 title="Supprimer ce message"> Supprimer</a><br></div>';
		t.popMsg.getMainDiv().innerHTML = m;
		t.popMsg.getTopDiv().innerHTML = '<DIV align=center><B>Messagerie</B></DIV>';
		t.popMsg.show(true);
	},

	DisplayRpt: function (){
		var t = Tabs.Rpt;
		var results = ById("idBoRptResultsDiv");
		if(!t.data.length) {
			results.innerHTML = '<center>Aucun resultat</center>';
			return;
		}
		var myAllianceId = parseInt(getMyAlliance()[0]);
		reportsSearched = t.data.length;
		reportsFound = 0;
		t.content = '';
		for (var i=0; i<reportsSearched;i++) {
			var reportId = t.data[i].reportId;
			var rpt = t.report[reportId];
			if ((rpt.side0Name=='undefined') && (rpt.marchName != 'Desertion'))
				continue;
			if ((((myAllianceId == parseInt(rpt.side1AllianceId) && Options.arAttacker != 'Them')
				|| (myAllianceId != parseInt(rpt.side1AllianceId) && Options.arAttacker != 'Us')
				|| Options.arAttacker == 'Both')
				&& ((myAllianceId == parseInt(rpt.side0AllianceId) && Options.arTarget != 'Them')
				|| (myAllianceId != parseInt(rpt.side0AllianceId) && Options.arTarget != 'Us')
				|| Options.arTarget == 'Both')
				&& ((Options.arAttack && (rpt.marchName == 'Attaque' || rpt.marchName == 'Defense'))
				|| (Options.arScout && (rpt.marchName == 'Contre-Ecl' || rpt.marchName == 'Eclaireur'))
				|| (Options.arReinforce && rpt.marchName == 'Renfort')
				|| (Options.arTransport && rpt.marchName == 'Transport')))
				|| (rpt.marchName == 'Desertion')) {
				if (((t.what == ''
					|| (rpt.side1Name.search(t.what, "i") != -1)
					|| (rpt.side1AllianceName.search(t.what, "i") != -1)
					|| (rpt.side0Name.search(t.what, "i") != -1)
					|| (rpt.side0AllianceName.search(t.what, "i") != -1)
					|| (rpt.side0TileTypeText.search(t.what, "i") != -1))
					&& (t.whatNot == ''
					|| ((rpt.side1Name.search(t.whatNot, "i") == -1)
					&& (rpt.side1AllianceName.search(t.whatNot, "i") == -1)
					&& (rpt.side0Name.search(t.whatNot, "i") == -1)
					&& (rpt.side0AllianceName.search(t.whatNot, "i") == -1)
					&& (rpt.side0TileTypeText.search(t.whatNot, "i") == -1))))
					|| (rpt.marchName == 'Desertion')) {
					
					if ((ById("idRptFiltre1").value=="") ||   (rpt.side0TileType==54 && ById("idRptFiltre1").value==54)  ||
					    (rpt.side0TileType>0 && rpt.side0TileType<51 && ById("idRptFiltre1").value==0)) {
					
					
					reportsFound++;
					if (reportsFound == 1) {
						t.content += '<center><table class=ptTabOverview width=100% cellspacing=0 cellpadding=3><thead><th>P</th><th>R.</th><th>Date</th><th>'+uW.g_js_strings.commonstr.attacker+'</th><th>De</th>';
						if (Options.arAttacker != 'Us')
							t.content += '<th>Alliance</th>';
						t.content += '<th>Action</th><th>'+uW.g_js_strings.commonstr.target+'</th><th>A</th>';
						if (Options.arTarget != 'Us')
							t.content += '<th>Alliance</th>';
						t.content += '<th>Type</th><th><span title="Ville la plus proche">VP</span></th><th><span title="Distance de la ville la plus proche">D</span></th></thead><tbody>';
					}
					
					
					var closestDist=999999;
					var closestLoc=null;
					var closestNum=1;
					for (var c=0; c<Cities.numCities; c++){
						var city = Cities.cities[c];
						var dist=distance(city.x,city.y,rpt.side0XCoord,rpt.side0YCoord);
						if(dist<closestDist) {
							closestDist=dist;
							closestLoc=city.x +','+ city.y;
							closestNum=c+1;
						}
					}
					if (rpt.marchName == 'Contre-Ecl' || rpt.marchName == 'Defense')
					 style=' style="background-color:#EF9999;"';
					else if (rpt.marchName == 'Renfort')
					 style=' style="background-color:#99EF99;"';
					else
					 style="";
					t.content += '<tr id="BOrpt'+ reportId +'"><td align=right '+style+'>'+rpt.page+'</td><td  align=right '+style+'><a onclick="getReport('+ reportId+')"><img  border=0 src="http://cdn1.iconfinder.com/data/icons/woothemesiconset/16/search_button.png"></a>';
					 if (rpt.side0Name==Seed.player.name || rpt.side1Name==Seed.player.name) {
					         t.content +='&nbsp;<a onclick="DelReport('+ reportId +', false);document.getElementById(\'BOrpt'+ reportId +'\').style.display=\'none\';"><img src="http://cdn1.iconfinder.com/data/icons/musthave/16/Remove.png" border=0 title="Supprimer mon rapport"></a>';
        					}
					t.content += '</td><td '+style+'>'+formatUnixTime(rpt.reportUnixTime,'24hour')+'</td>';
					if (rpt.marchName == 'Desertion') {
						t.content += '<td '+style+'></td><td '+style+'></td>';
						if (Options.arAttacker != 'Us')
							t.content += '<td '+style+'></td>';
						t.content += '<td '+style+'>'+rpt.marchName+'</td><td '+style+'></td><td '+style+'></td><td '+style+'></td>';
						if (Options.arAttacker != 'Us')
							t.content += '<td '+style+'></td>';
						t.content += '<td '+style+'></td><td '+style+'></td>';
						} else {
						t.content += '<td '+style+'><span title="'+rpt.side1Name+'">'+rpt.side1Name.substring(0,12)+'</span></td><td align=center '+style+'><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a></td>';
						if (Options.arAttacker != 'Us')
						t.content += '<td '+style+'><span title="'+rpt.side1AllianceName+'">'+rpt.side1AllianceName.substring(0,17)+'</span></td>';
						            if (rpt.marchName == 'Contre-Ecl' || rpt.marchName == 'Eclaireur')
						             t.content += '<TD '+style+'><FONT color="FF8822">'+rpt.marchName+'</font></td>';
							    else if (rpt.marchName == 'Attaque' || rpt.marchName == 'Defense')
							     t.content += '<TD '+style+'><FONT color="FF1122">'+rpt.marchName+'</font></td>';
							    else if (rpt.marchName == 'Renfort')
	      					 	     t.content += '<TD '+style+'><FONT color="339933">'+rpt.marchName+'</font></td>';
	      					 	    else
	      					 	     t.content += '<TD '+style+'>'+rpt.marchName+'</td>';
						//t.content += '<td>'+rpt.marchName+'</td>';
						t.content += '<td '+style+'><span title="'+rpt.side0Name+'">'+rpt.side0Name.substring(0,12)+'</span></td>';
						t.content += '<td align=center '+style+'><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a></td>';
						if (Options.arTarget != 'Us')
							t.content += '<td '+style+'><span title="'+rpt.side0AllianceName+'">'+rpt.side0AllianceName.substring(0,17)+'</span></td>';
						t.content += '<td '+style+'>'+rpt.side0TileTypeLevel+'</td><td align=center '+style+'><A onclick=\"citysel_click(document.getElementById(\'citysel_'+ (closestNum)+'\'));\">' + closestLoc + '</a></td><td align=right '+style+'>'+Math.floor(closestDist)+'</td></tr>';
					}
				}	
				}
			}
		}
		if (reportsFound > 1)
			t.content += '</tbody></table></center>';
		if (reportsFound == 0 && reportsSearched > 0)
			t.content = '<center>Aucun resultat</center>';
		results.innerHTML = t.content;
		ById("idRptSearched").innerHTML = '&nbsp;Resultat : ' + reportsSearched;
		ById("idRptFound").innerHTML = 'Trouve : ' + reportsFound;
	},

	getReportBody: function(reportId){
		var t = Tabs.Rpt;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.rid=reportId;
		params.side=t.report[reportId].sideId;
		if (params.side > -1) {
			new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchReport.php" + unsafeWindow.g_ajaxsuffix, {
				method: "post",
				parameters: params,
				onSuccess: function (rslt) {
					t.displayReportBody(rslt,reportId);
				},
				onFailure: function (rslt) {},
			}, false);
		} else {
			
		}
	},

	displayReportBody: function (rslt, reportId) {
		var t = Tabs.Rpt;
		var popReport = null;
		var rpt = t.report[reportId];
		var m = '';
		var fortmight = {u53: "4",u55: "7",u60: "1",u61: "2",u62: "3",    };
		var unitImg = [];
		var puipui=new Array();
		for (var ui = 1 ; ui<13; ui++)
		 puipui.push(uW.unitmight['unt'+ui]);
		puipui[53] = fortmight['u53'];
		puipui[55] = fortmight['u55'];
		puipui[60] = fortmight['u60'];
		puipui[61] = fortmight['u61'];
		puipui[62] = fortmight['u62'];
		ordre_grandeur=0;
		delta_perte=0;
		var perte_atk = 0;
		var perte_def = 0;
		for (var i=1;i<13;i++)
			unitImg[i] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+i+'_30_s34.jpg title="'+uW.unitcost['unt'+i][0]+'"></TD><TD>' + uW.unitcost['unt'+i][0].substr(0,10);
		for (var i=101;i<111;i++)
			unitImg[i] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+i+'_30.jpg title="'+uW.g_js_strings.monsterUnitsNames['m'+i]+'"></TD><TD>' + uW.g_js_strings.monsterUnitsNames['m'+i].substr(0,10);
	        unitImg[53] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_53_30.png></TD><TD>'+ uW.fortcost.frt53[0];
		unitImg[55] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_55_30.png></TD><TD>'+ uW.fortcost.frt55[0];
		unitImg[60] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_60_30.png></TD><TD>'+ uW.fortcost.frt60[0];
		unitImg[61] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_61_30.png></TD><TD>'+ uW.fortcost.frt61[0];
		unitImg[62] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_62_30.png></TD><TD>' + uW.fortcost.frt62[0];
		goldImg = '<img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_30.png></TD><TD>' + uW.g_js_strings.commonstr.gold;;
		foodImg = '<img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png></TD><TD>' + uW.g_js_strings.commonstr.food;
		woodImg = '<img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png></TD><TD>' + uW.g_js_strings.commonstr.wood;;
		stoneImg = '<img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png></TD><TD>' + uW.g_js_strings.commonstr.stone;;
		oreImg = '<img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png></TD><TD>' + uW.g_js_strings.commonstr.ore;;
		aetherstoneImg = '<img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png></TD><TD>'+ uW.g_js_strings.commonstr.aetherstone;
		
		function buildHeader () {
			var h='<TABLE class=ptTab width=100%>';
			h+='<TR valign=top><TD align=left width=10%><B>';
			if (rpt.marchName == 'Contre-Ecl')
			 h+=uW.g_js_strings.commonstr.location+" " + uW.g_js_strings.modal_messages_viewreports_view.antiscoutingat+' ';
			else if (rpt.marchName == 'Eclaireur')
				h+=uW.g_js_strings.modal_messages_viewreports_view.scoutrpt+' ';
			else if (rpt.marchName == 'Attaque' || rpt.marchName == 'Defense')
				h+=uW.g_js_strings.modal_messages_viewreports_view.battleat+' ';
				
			else if (rpt.marchName == 'Renfort' || rpt.marchName == 'Transport')
				h+=rpt.marchName+' depuis<BR />'+rpt.marchName+' vers</B>';
			else if (rpt.marchName == 'Transport')
			  h+=rpt.marchName+' depuis<BR />'+uW.g_js_strings.modal_messages_viewreports_view.transpto+'</B>';
			if (rpt.side0TileTypeText == 'Barb')
				h+=' Camp Barbare '+uW.g_js_strings.commonstr.level+' ' + rpt.side0TileLevel;
			else if (rpt.side0TileTypeText != 'Ville')
				h+=' '+rpt.side0TileTypeText+' '+uW.g_js_strings.commonstr.level+' '+ rpt.side0TileLevel+' ';
			h+='</B>';
			if (rpt.marchName == 'Attaque' || rpt.marchName == 'Defense' || rpt.marchName == 'Contre-Ecl' || rpt.marchName == 'Eclaireur')
			 if (rslt['displayGlory']!==undefined)
			   h+='<br><B>'+uW.g_js_strings.commonstr.glory+' : <font color=red>'+rslt['glory']+'</font></B>';
				
			h+='</td>';
			if (rpt.marchName == 'Renfort' || rpt.marchName == 'Transport') {
				h+='<TD align=left width=1%>';
				if (Seed.player.name != rpt.side1Name)
					h+=rpt.side1Name;
				if (Seed.player.name != rpt.side0Name)
					h+='<BR />'+rpt.side0Name;
				h+='</TD>';
			}
			h+='<TD align=left width=5%>';

			if (rpt.marchName == 'Renfort' || rpt.marchName == 'Transport')
				h+='<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a><BR />';
			h+='<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a></TD>';

			if (rpt.side0TileTypeText != 'Ville' && rpt.side0TileTypeText != 'Barb' && (rpt.marchName == 'Attaque' || rpt.marchName == 'Defense')) {
				if (rslt['conquered']==1)
					h+='<TD><FONT color="#CC0000"><B>'+uW.g_js_strings.commonstr.conquered+'</B></font></td>';
				else if (rslt['conquered']==0)
					h+='<TD><FONT color="#66CC33"><B>S&eacute;curis&eacute;</B></font></td>';
			} else if (rpt.marchName == 'Renfort' || rpt.marchName == 'Transport') {
				h+='<TD align=left width=5%>'+rpt.side1CityName+'<BR />';
				if (rpt.side0CityName != '')
					h+=rpt.side0CityName+'</TD>';
				else
					h+=rpt.side0TileTypeText+' Niveau '+ rpt.side0TileLevel+'</TD>';
			}

			h+='<TD align=right>' + formatUnixTime(rpt.reportUnixTime,'24hour') + '<BR />&nbsp;';
			if (rpt.side0Name==Seed.player.name || rpt.side1Name==Seed.player.name)
			  h+='<a onclick="DelReport('+ reportId +', false);ById(\'BOrpt'+ reportId +'\').style.display=\'none\';ById(\'pbShowOther_X\').click();"><img src="http://cdn1.iconfinder.com/data/icons/musthave/16/Remove.png" border=0 title="Supprimer mon rapport"></a>';
			
			h+='&nbsp;'+uW.g_js_strings.modal_messages_viewreports_view.reportno+': ' + reportId + '</TD></TR></TABLE>';
			return h;
		}

		function handleunts () { // Troops sent to Reinforce or troops found on a Scout
			var hunts = '', th = '', tc = '', tf = '';
			if (rslt['unts'] != undefined) {
				if (rpt.marchName == 'Renfort')
					th='<TABLE class=ptTab><TR><TH colspan=3 align=left>Renforts Envoy&eacute;s</TH></TR>';
				else if (rslt['unts']['u1'] != undefined || rslt['unts']['u2'] != undefined || rslt['unts']['u3'] != undefined || rslt['unts']['u4'] != undefined || rslt['unts']['u5'] != undefined || rslt['unts']['u6'] != undefined || rslt['unts']['u7'] != undefined || rslt['unts']['u8'] != undefined || rslt['unts']['u9'] != undefined || rslt['unts']['u10'] != undefined || rslt['unts']['u11'] != undefined || rslt['unts']['u12'] != undefined)
					th='<TABLE class=ptTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.troops+'</TH></TR>';
				for (var i=1;i<13;i++)
					if (rslt['unts']['u'+i] != undefined)
						tc+='<TR><TD>' + unitImg[i] + '</TD><TD align=right>'+addCommas(rslt['unts']['u'+i])+'</TD></TR>';
				
				tf='</TABLE>';
			}
			if (tc != '')
				hunts = th + tc + tf;
			return hunts;
		}

		function handlersc () { // Resources brought with reinforcements or found on a Scout
			var hrsc = '', th = '', tc = '', tf = '';
			if (rslt['rsc'] != undefined) {
				if (rslt['rsc']['r1'] > 0 || rslt['rsc']['r2'] > 0 || rslt['rsc']['r3'] > 0 || rslt['rsc']['r4'] > 0) {
					if (rpt.marchName == 'Renfort')
						th='<TABLE class=ptTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.resources+'</TH></TR>';
					else {
						th='<TABLE class=ptTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.resources+'</TH></TR>';
						if (rslt['gld'] > 0)
							tc+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommasInt(rslt['gld'])+'</TD></TR>';
					}
					if (rslt['rsc']['r1'] > 0)
						tc+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r1'])+'</TD></TR>';
					if (rslt['rsc']['r2'] > 0)
						tc+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r2'])+'</TD></TR>';
					if (rslt['rsc']['r3'] > 0)
						tc+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r3'])+'</TD></TR>';
					if (rslt['rsc']['r4'] > 0)
						tc+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r4'])+'</TD></TR>';
					tf='</TABLE>';
				}
			}
			if (tc != '')
				hrsc = th + tc + tf;
			return hrsc;
		}

		function handlefrt () { // Fortifications found on a Scout
			var hfrt = '', th = '', tc = '', tf = '';
			if (rslt['frt'] != undefined) {
				if (rslt['frt']['f53'] != undefined || rslt['frt']['f55'] != undefined || rslt['frt']['f60'] != undefined || rslt['frt']['f61'] != undefined || rslt['frt']['f62'] != undefined) {
					th='<TABLE class=ptTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.modal_openWalls.walldef+'</TH></TR>';
					if (rslt['frt']['f53'] != undefined)
						tc+='<TR><TD>' + unitImg[53] + '</TD><TD align=right>'+addCommas(rslt['frt']['f53'])+'</TD></TR>';
					if (rslt['frt']['f55'] != undefined)
						tc+='<TR><TD>' + unitImg[55] + '</TD><TD align=right>'+addCommas(rslt['frt']['f55'])+'</TD></TR>';
					if (rslt['frt']['f60'] != undefined)
						tc+='<TR><TD>' + unitImg[60] + '</TD><TD align=right>'+addCommas(rslt['frt']['f60'])+'</TD></TR>';
					if (rslt['frt']['f61'] != undefined)
						tc+='<TR><TD>' + unitImg[61] + '</TD><TD align=right>'+addCommas(rslt['frt']['f61'])+'</TD></TR>';
					if (rslt['frt']['f62'] != undefined)
						tc+='<TR><TD>' + unitImg[62] + '</TD><TD align=right>'+addCommas(rslt['frt']['f62'])+'</TD></TR>';
					tf='</TABLE>';
				}
			}
			if (tc != '')
				hfrt = th + tc + tf;
			return hfrt;
		}

		function handleblds (bType) {
		     if (rslt['blds'] != undefined) {
		
			var blds = rslt['blds']['b'+bType]; 
			var couleur='';
			if (bType==8) couleur=' style="background-color:red"';
			b = '<TR><TD '+couleur+'>'; arField = [], firstbld = true;
			b+=unsafeWindow.buildingcost["bdg"+bType][0]+'</TD><TD '+couleur+'>';
			for (var i=1; i<12; i++)
				arField[i]=0;
			for (var i=0; i < blds.length; i++)
				arField[blds[i]]++
			for (var i=11; i>0; i--) {
				if (arField[i] > 0) {
					if (firstbld)
						firstbld = false;
					else
						b+=', ';
					if (arField[i] > 1)
						b+=arField[i] + ' x ';
					b+=' ' + i;
				}
			}
			b+='</TD></TR>';
		       } else {
		        b='';
		       }
		       return b;
		}

    	if (t.popReport == null) {
 		if (rpt.marchName == 'Renfort') {
			t.popReport = new CPopup('pbShowRein', 0, 0, 425, 340, true, function() {clearTimeout (1000);});
			m+= '<DIV style="height:285px">';
		} else if (rpt.marchName == 'Transport') {
			t.popReport = new CPopup('pbShowTrans', 0, 0, 525, 240, true, function() {clearTimeout (1000);});
			m+= '<DIV style="height:185px">';
		} else if (rpt.marchName == 'Eclaireur' && rslt['winner']==1 && rpt.sideId==1){
			t.popReport = new CPopup('pbShowOther', 0, 0, 550, 500, true, function() {clearTimeout (1000);});
			m+= '<DIV style="max-height:485px; height:485px; overflow-y:scroll">';
		} else {
			t.popReport = new CPopup('pbShowOther', 0, 0, 630, 440, true, function() {clearTimeout (1000);});
			m+= '<DIV style="max-height:423px; height:423px; overflow-y:scroll">';
		}
		t.popReport.centerMe (mainPop.getMainDiv());
	        t.popReport.autoHeight (true); 
	      }
		m+=buildHeader();

		if (rpt.marchName == 'Transport') { // Transport
			m+='<TABLE class=ptTab>'; // Only transports have these in rslt, so handle them here
			if (parseInt(rslt['gold']) > 0)
				m+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommas(rslt['gold'])+'</TD></TR>';
			if (parseInt(rslt['resource1']) > 0)
				m+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommas(rslt['resource1'])+'</TD></TR>';
			if (parseInt(rslt['resource2']) > 0)
				m+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommas(rslt['resource2'])+'</TD></TR>';
			if (parseInt(rslt['resource3']) > 0)
				m+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommas(rslt['resource3'])+'</TD></TR>';
			if (parseInt(rslt['resource4']) > 0)
				m+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommas(rslt['resource4'])+'</TD></TR>';
			if (parseInt(rslt['resource5'])> 0)
				m+='<TR><TD>'+aetherstoneImg+'</TD><TD align=right>'+addCommas(rslt['resource5'])+'</TD></TR>';
			m+='</TABLE>';
		}

		m+='<TABLE class=ptTab>';
		if ((rslt['winner']==1 && rpt.sideId==0) || (rslt['winner']==0 && rpt.sideId==1)) {
			if (rpt.marchName == 'Eclaireur')
				m+='<TR><TD><FONT color="#CC0000"><B>'+uW.g_js_strings.modal_messages_viewreports_view.scoutfail+'</B></font></TD></TR>';
			else
				m+='<TR><TD><FONT color="#CC0000"><B>'+uW.g_js_strings.commonstr.defeat+'</B></font></TD></TR>';
		}
		if (rslt['winner']==0 && rpt.sideId==0)
			m+='<TR><TD><FONT color="#66CC33"><B>'+uW.g_js_strings.commonstr.victory+' !</B></font></TD></TR>';
		if (rslt['winner']==1 && rpt.sideId==1)
			m+='<TR><TD><FONT color="#66BB33"><B>'+uW.g_js_strings.commonstr.victory+' !</B></font></TD></TR>';
		
		if (rslt['wall'] != undefined) {
			
				
			if (rslt['wall'] > 0 && rslt['wall'] < 100)
				m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.wallbreach+' '+rslt['wall']+' '+uW.g_js_strings.modal_messages_viewreports_view.percdamage+'</TD></TR>';
			else
				m+='<TR><TD>'+ uW.g_js_strings.modal_messages_viewreports_view.wallbreach+'</TD></TR>';
		}
		m+= '</TABLE><BR />';
		if (rslt['wonGloryItem']) {
		  m+="<TABLE class=ptTab><TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/" + rslt['wonGloryItem'] + ".jpg></td><td colspan=2>"+unsafeWindow.ksoItems[rslt['wonGloryItem']].name+"</td></tr></TABLE><BR />";
		}
		
		if (rslt['throneRoomDrop']) {
		  var A=rslt['throneRoomDrop'];
		  faction=A.faction;
		  if (unsafeWindow.kocThroneItems[rslt['throneRoomDrop'].id]) {
       	           var name=unsafeWindow.kocThroneItems[rslt['throneRoomDrop'].id].name;
       	         
		  m+="<TABLE class=ptTab><TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+faction.replace('briton','britton')+"/"+faction.replace('briton','britton')+"_"+A.type+"_normal_1.png></td><td colspan=2>"+name+"</td></tr></TABLE><BR />";
		 }
		}
		if (rslt['loot'] != undefined) {
			m+='<TABLE class=ptTab>';
			if (rslt['loot'][0] > 0)
				m+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommas(rslt['loot'][0])+'</TD></TR>';
			if (rslt['loot'][1] > 0)
				m+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommas(rslt['loot'][1])+'</TD></TR>';
			if (rslt['loot'][2] > 0)
				m+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommas(rslt['loot'][2])+'</TD></TR>';
			if (rslt['loot'][3] > 0)
				m+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommas(rslt['loot'][3])+'</TD></TR>';
			if (rslt['loot'][4] > 0)
				m+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommas(rslt['loot'][4])+'</TD></TR>';
			if (rslt['loot'][6] > 0)
				m+='<TR><TD>'+aetherstoneImg+'</TD><TD align=right>'+addCommas(rslt['loot'][6])+'</TD></TR>';
			if (rslt['loot'][5] !== undefined) {
				var q=unsafeWindow.Object.keys(rslt['loot'][5]);
				if (q.length>0) {
				 for(var u=0,y=q.length;u<y;++u){
				 C=q[u];
				 if (unsafeWindow.ksoItems[C]!==undefined) 
				  m+="<TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/" + C + ".jpg></td><td colspan=2>"+unsafeWindow.ksoItems[C].name+"</td></tr>";
			        }
			        }
				
			}
			
			m+='</TABLE><BR />';
		}

		if (rpt.marchName == 'Renfort') {
			m+=handleunts();
			m+=handlersc();
		}

		if (rpt.marchName == 'Eclaireur' && rslt['winner']==1) {
			m+='<TABLE class=ptTab width=100%><TR><TD width=50% align=left valign=top>';
			m+=handleunts();
			if (rpt.side0TileTypeText!='F.S.')  m+=handlefrt();			
			 m+=handlersc();
			m+='</TD><TD width=50% align=left valign=top>';
			if (rpt.side0TileTypeText!='F.S.') {
			m+='<TABLE class=ptTab width=100%>';
			if (rslt['lstlgn'] != undefined) {
				if (!rslt['lstlgn'])
					m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+' : -</TD></TR>';
				else
					m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+' : ' + formatUnixTime(rslt['lstlgn']) + '</TD></TR>';
			}
			m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+' : ';
			if (rslt['knt'] != undefined)
				m+=rslt['knt']['cbt'];
			else
				m+='None';
			m+='</TD></TR>';
			
			if (rslt['pop'] != undefined)
				m+='<TR><TD>'+uW.g_js_strings.commonstr.population+' : ' + addCommas(rslt['pop']) + '</TD></TR>';
			if (rslt['hap'] != undefined)
				m+='<TR><TD>'+uW.g_js_strings.commonstr.happiness+' : ' + addCommas(rslt['hap']) + '</TD></TR></TABLE>';
			
			 if (rslt['blds'] != undefined) {
				m+='<b><a id=BORptBatClick>'+uW.g_js_strings.commonstr.buildings+'</a></b><br><TABLE class=ptTab id=BORptBat style="display:none">';
				for (var i=0; i<53; i++)
					if (rslt['blds']['b'+i] != undefined)
						m+=handleblds(i);
				m+='</TABLE>';
			 }
			 if (rslt['tch'] != undefined) {
				m+='<b><a id=BORptRechercheClick>'+uW.g_js_strings.commonstr.technology+'</a></b><br><TABLE class=ptTab id=BORptRecherche style="display:none">';
				for (var tl=1; tl < 17; tl++)
					if (tl != 7)
						m+='</TD></TR><TR><TD>'+researchLevels[tl].Name+'</TD><TD align=right>' + rslt['tch']['t'+tl] + '</TD></TR>';
				m+='</TABLE>';
			 }
			}
			m+='</TD></TR></TABLE><br><input type=button value="Export to Combat" id=BOExportCombat>';
		}

		if (rslt['fght'] != undefined){
			m+='<TABLE class=ptTab width=100%><TR><TD width=50% align=left valign=top>';
			m+='<TABLE class=ptTab width=100%>';
			m+='<TR><TD colspan=4><B>'+uW.g_js_strings.commonstr.attacker+'</B> ('+rpt.side1Name+')';
			if (rslt['winner']==1)
				m+='<FONT color="#CC0000"><B> '+uW.g_js_strings.commonstr.winner+'</B></FONT>';
			m+='</TD></TR>';
			if (rpt.marchName == 'Attaque' || rpt.marchName == 'Defense')
				m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+' : ' + rslt['s1KCombatLv'] + '</TD></TR>';
			if (rslt['s1atkBoost']!== undefined)
			 if (100*rslt['s1atkBoost']>0)
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.attackboosted+' : ' + 100*rslt['s1atkBoost'] + '%</TD></TR>';
			if (rslt['s1defBoost']!== undefined)
			 if (100*rslt['s1defBoost']>0) 
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.defenseboosted+' : ' + 100*rslt['s1defBoost'] + '%</TD></TR>';
			if (rslt['s1lifeBoost']!== undefined)
			 if (100*rslt['s1lifeBoost']>0)
			  m+='<TR><TD colspan=4>Vie : ' + 100*rslt['s1lifeBoost'] + '%</TD></TR>';
			if (rslt['s1guardianDefBoost']!== undefined)
			 if (100*rslt['s1guardianDefBoost']>0)
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_defenseboosted+' : ' + 100*rslt['s1guardianDefBoost'] + '%</TD></TR>';
			if (rslt['s1guardianAtkBoost']!== undefined)
			 if ( 100*rslt['s1guardianAtkBoost']>0)
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_attackboosted+' : ' + 100*rslt['s1guardianAtkBoost'] + '%</TD></TR>';
			if (rslt['s1guardianMarchBoost']!== undefined)
			 if (100*rslt['s1guardianMarchBoost']>0)
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_marchboosted+' : ' + 100*rslt['s1guardianMarchBoost'] + '%</TD></TR>';
			m+='<TR><TD colspan=4><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a> ' + rpt.side1CityName + '</TD></TR>';
			if (rslt['fght']["s1"] != undefined) {
				m+='<TR><TH></TH><TH align=left>'+uW.g_js_strings.commonstr.troops+'</TH><TH align=right>Battu</TH><TH align=right>Survivant</TH><TH align=right>Tu&eacute;(e)</TH></TR>';
				for (var i=1;i<13;i++) {
					if (rslt['fght']["s1"]['u'+i] != undefined) {
						if (rslt['fght']["s1"]['u'+i][0] > rslt['fght']["s1"]['u'+i][1]) {
							perte_atk= perte_atk +(rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1])*puipui[i-1];
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s1"]['u'+i][1])+'</FONT></td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1])+'</FONT></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][1])+'</td></tr>';
						}
					}
				}
			}
			m+='</TABLE><br>';
			// Bonus divers ^^^
			if (rslt['s1ThroneRoomBoosts']) {
			m+='<b><a id=BORptS1ThroneClick>Bonus de la salle du tr&ocirc;ne</a></b><br><TABLE class=ptTab id=BORptS1Throne style="display:none">';
			  for (var i in rslt['s1ThroneRoomBoosts']) {
	
			   m+='<TR><TD><B>'+uW.cm.thronestats.effects[i][1]+'</B></td><td align=right>'+ rslt['s1ThroneRoomBoosts'][i] +' %</td></tr>'; 
			 
			  }
			m+='</TABLE>';
			}else{
				  m+='<b>Aucun bonus de la salle du tr&ocirc;ne</b>';
			}
			
			m+='</TD><TD width=50% align=left valign=top>';
			m+='<TABLE class=ptTab width=100%>';
			m+='<TR><TD colspan=4><B>'+uW.g_js_strings.commonstr.defenders+'</B> ('+rpt.side0Name+')';
			if (rslt['winner']==0)
				m+='<FONT color="#CC0000"><B> '+uW.g_js_strings.commonstr.winner+'</B></FONT>';
			m+='</TD></TR>';
			if (rpt.marchName == 'Attaque' || rpt.marchName == 'Defense')
				m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+' : ' + rslt['s0KCombatLv'] + '</TD></TR>';
			if (rslt['s0atkBoost'] !== undefined)
			 if (100*rslt['s0atkBoost']>0)
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.attackboosted+' : ' + 100*rslt['s0atkBoost'] + '%</TD></TR>';
			if (rslt['s0defBoost'] !== undefined)
			 if (rslt['s0defBoost']>0)
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.defenseboosted+' : ' + 100*rslt['s0defBoost'] + '%</TD></TR>';
			if (rslt['s0lifeBoost']!== undefined)
			 if (100*rslt['s0lifeBoost']>0)
			  m+='<TR><TD colspan=4>Vie : ' + 100*rslt['s0lifeBoost'] + '%</TD></TR>';
			if (rslt['s0guardianDefBoost']!== undefined)
			 if (100*rslt['s0guardianDefBoost']>0)
			 m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_defenseboosted+' : ' + 100*rslt['s0guardianDefBoost'] + '%</TD></TR>';
			if (rslt['s0guardianAtkBoost']!== undefined)
			 if (100*rslt['s0guardianAtkBoost']>0)
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_attackboosted+' : ' + 100*rslt['s0guardianAtkBoost'] + '%</TD></TR>';
			if (rslt['s0guardianMarchBoost']!== undefined)
			 if (100*rslt['s0guardianMarchBoost'])
			  m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_marchboosted+' : ' + 100*rslt['s0guardianMarchBoost'] + '%</TD></TR>';
			if (rslt['rnds']!==undefined)
			   m+='<TR><TD colspan=4>Tour : ' + rslt['rnds'] + '</TD></TR>';
			if (rslt['fght']["s0"] != undefined) {
				m+='<TR><TH></TH><TH align=left>'+uW.g_js_strings.commonstr.troops+'</TH><TH align=right>Battu</TH><TH align=right>Survivant</TH></TR>';
				for (var i=1;i<13;i++) {
					if (rslt['fght']["s0"]['u'+i] != undefined) {
						if (rslt['fght']["s0"]['u'+i][0] > rslt['fght']["s0"]['u'+i][1]) {
							perte_def= perte_def +(rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1])*puipui[i-1];
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['u'+i][1])+'</FONT></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][1])+'</td></tr>';
						}
					}
				}
				// Dark Forest
							for (var i=101;i<111;i++) {
									if (rslt['fght']["s0"]['m'+i] != undefined) {
										if (rslt['fght']["s0"]['m'+i][0] > rslt['fght']["s0"]['m'+i][1]) {
											m+='<TR><TD>' + unitImg[i] + '</td>';
											m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][0])+'</td>';
											m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['m'+i][1])+'</FONT></td></tr>';
										} else {
											m+='<TR><TD>' + unitImg[i] + '</td>';
											m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][0])+'</td>';
											m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][1])+'</td></tr>';
										}
									}
				}
				//
				for (var i=53;i<=55;i++) {
					if (rslt['fght']["s0"]['f'+i] != undefined) {
						if (rslt['fght']["s0"]['f'+i][0] > rslt['fght']["s0"]['f'+i][1]) {
							perte_def= perte_def +(rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1])*puipui[i];
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</font></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</td></tr>';
						}
					}
				}
				for (var i=60;i<=63;i++) {
					if (rslt['fght']["s0"]['f'+i] != undefined) {
						if (rslt['fght']["s0"]['f'+i][0] > rslt['fght']["s0"]['f'+i][1]) {
							perte_def= perte_def +(rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1])*puipui[i];
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
							m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</font></td></tr>';
						} else {
							m+='<TR><TD>' + unitImg[i] + '</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
							m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</td></tr>';
						}
					}
				}
			} else
				m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.notroopsdef+'</TD></TR>';
			m+='</TABLE><br>';
			// Bonus divers ^^^
			if (rslt['s0ThroneRoomBoosts']) {
			m+='<b><a id=BORptS0ThroneClick>Bonus de la salle du tr&ocirc;ne</a></b><br><TABLE class=ptTab id=BORptS0Throne style="display:none">';
			  for (var i in rslt['s0ThroneRoomBoosts']) {
	
			   m+='<TR><TD><B>'+uW.cm.thronestats.effects[i][1]+'</B></td><td align=right>'+ rslt['s0ThroneRoomBoosts'][i] +' %</td></tr>'; 
			 
			  }
			
			m+='</TABLE>';
				
			}else{
			  m+='<b>Aucun bonus de la salle du tr&ocirc;ne</b>'
			}
			
			m+='</TD></TR>';
			delta_perte = perte_atk - perte_def;
			delta_pos = 1;
			ordre_grandeur = 1; //par defaut: perte en k
			delta_perte = delta_perte/1000;
			if (delta_perte<0){
				delta_pos = -1; //plus de perte pour def
				delta_perte = Math.abs(delta_perte);
			}
			if (delta_perte>1000) { //perte en Mega
				ordre_grandeur = 2;
				delta_perte = entier_1dec(delta_perte/1000);
			}
			if (delta_perte<1) { // pertes inferiereures ÃƒÂ  1 k
				ordre_grandeur = 0;
				delta_perte = entier_1dec(delta_perte*1000);
			}
			if (ordre_grandeur == 1) { //perte en kilo => garde 1chiffre apres virgule
				delta_perte = entier_1dec(delta_perte);
			}
			// transforme les pertes en kilo (avec 1 chiffre derriere virgule)
			perte_atk = entier_1dec(perte_atk/1000);
			perte_def = entier_1dec(perte_def/1000);
			
			m+='<TR><TD colspan=4>&nbsp;</TD></TR>';
			// affichage 
			if ((delta_pos == 1) && (delta_perte != 0)) {
				m+='<TR><TD><FONT color="#000"><b>'+uW.g_js_strings.commonstr.might+' Perdu</b> ('+rpt.side1Name+') : </FONT><FONT color="#CC0000"> '+(perte_atk)+'k</FONT></TD><TD><FONT color="#00"><b>'+uW.g_js_strings.commonstr.might+' Perdu</b> ('+rpt.side0Name+') : '+perte_def+'k </FONT></TD></TR>';
				if (ordre_grandeur==2) {
					m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">Pertes superieures de :</FONT><FONT color="#CC0000"> '+delta_perte+'M</FONT></TD><TD></TD></TR></table>';
				} else if (ordre_grandeur==1){
					m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">Pertes superieures de :</FONT><FONT color="#CC0000"> '+delta_perte+'k </FONT></TD><TD></TD></TR></table>';
				} else if(ordre_grandeur==0){
					m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">Pertes superieures de :</FONT><FONT color="#CC0000"> '+delta_perte+'</FONT></TD><TD></TD></TR></table>';
				}
			}
			if ((delta_pos == -1) && (delta_perte != 0)) {
				m+='<TR><TD><FONT color="#000"><b>'+uW.g_js_strings.commonstr.might+' Perdu</b> ('+rpt.side1Name+') : '+perte_atk+'k</FONT></TD><TD><FONT color="#000"><b>'+uW.g_js_strings.commonstr.might+' Perdu</b> ('+rpt.side0Name+') : </FONT><FONT color="#CC0000"> '+perte_def+'k </FONT></TD></TR>';
				if (ordre_grandeur==2) {
					m+='<TR><TD></TD><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">Pertes superieures de :</FONT><FONT color="#CC0000"> '+delta_perte+'M</FONT></TD></TR></table>';
				} else if (ordre_grandeur==1){
					m+='<TR><TD></TD><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">Pertes superieures de :</FONT><FONT color="#CC0000"> '+delta_perte+'k</FONT></TD></TR></table>';
				} else if (ordre_grandeur==0){
					m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">Pertes superieures de :</FONT><FONT color="#CC0000"> '+delta_perte+'</FONT></TD><TD></TD></TR></table>';
				}
			}
			if (delta_perte == 0 && (perte_def>0 || perte_atk>0)) {
				m+='<TR><TD><FONT color="#000"><b>'+uW.g_js_strings.commonstr.might+' Perdu</b> ('+rpt.side1Name+') : '+perte_atk+'k</FONT></TD><TD><FONT color="#000"><b>'+uW.g_js_strings.commonstr.might+' Perdu</b> ('+rpt.side0Name+') : '+perte_def+'k </FONT></TD></TR></TABLE>';		
			}
		}

		m+='</DIV>';
		t.popReport.getMainDiv().innerHTML = m;
		t.popReport.getTopDiv().innerHTML = '<DIV align=center><B>'+uW.g_js_strings.commonstr.report+'</B></DIV>';
	        t.popReport.show(true);
    		t.popReport.autoHeight (true); 
    		if (ById('BORptS0ThroneClick')) {
				 ById('BORptS0ThroneClick').addEventListener('click', function () {
				    		  if (ById('BORptS0Throne').style.display=="none") {ById('BORptS0Throne').style.display="block";} else {ById('BORptS0Throne').style.display="none";}
				 },false);
    		}
    		if (ById('BORptS1ThroneClick')) {
		 ById('BORptS1ThroneClick').addEventListener('click', function () {
		    		  if (ById('BORptS1Throne').style.display=="none") {ById('BORptS1Throne').style.display="block";} else {ById('BORptS1Throne').style.display="none";}
		 },false);
    		}
    		if (ById('BORptBatClick')) {
		 ById('BORptBatClick').addEventListener('click', function () {
		    		  if (ById('BORptBat').style.display=="none") {ById('BORptBat').style.display="block";} else {ById('BORptBat').style.display="none";}
		 },false);
    		}
    		if (ById('BORptRechercheClick')) {
    		 ById('BORptRechercheClick').addEventListener('click', function () {
    		  if (ById('BORptRecherche').style.display=="none") {ById('BORptRecherche').style.display="block";} else {ById('BORptRecherche').style.display="none";}
    		 },false);
    		}
    		if (ById('BOExportCombat')) {
    		 ById('BOExportCombat').addEventListener('click', function () {
      		 if (rslt['unts'] != undefined) {
    		  var A=0;
    		  for(var troops in unsafeWindow.unitcost){
    		   A++;
    		   if (ById('pbcombatd_'+troops)) {
    		    if  (rslt['unts']['u'+A] != undefined)
    		      ById('pbcombatd_'+troops).value=rslt['unts']['u'+A];
    		    else
    		      ById('pbcombatd_'+troops).value=0; 
    		   }
    		  }
    		 }
    		 // on remplit la technologie de la defenses
    		 if (rslt['tch'] != undefined) {
    		  CombatOptions.research[0]['tch8']=rslt['tch']['t8'];
    		  CombatOptions.research[0]['tch9']=rslt['tch']['t9'];
    		  CombatOptions.research[0]['tch13']=rslt['tch']['t13'];
    		  CombatOptions.research[0]['tch15']=rslt['tch']['t15'];
    		 }
    		 // chevalier
    		 if (rslt['knt'] != undefined) CombatOptions.knt[0] = rslt['knt']['cbt'];
    		 
    		 myBO.Combat.e_calculate();
    		 
    		 saveCombatOptions();
    		 
    		 }, false);
    		
    		
    		}
    		
    		
	},

};

Tabs.Marches = {
  tabOrder: 3,
  tabLabel: uW.g_js_strings.commonstr.march,
  cont:null,
  displayTimer:null,
  curTabBut : null,
  curTabName : null,
  state : null,
  
  hide : function (){
      var t = Tabs.Marches;
      clearTimeout (t.displayTimer);
  },
  
  show : function (){
   var t = Tabs.Marches;
       clearTimeout (t.displayTimer);
       if (t.curTabName == 'Z')
         t.showReinforcementsOut();
       else if (t.curTabName == 'R')
         t.showReinforcements();
       else if (t.curTabName == 'M')
         t.showMarches(9);
       else
      t.showAttacks();
  },
  init : function (div){  
    var t = Tabs.Marches; 
    t.cont = div;
    uW.pr58Recall = t.ajaxRecall;
    uW.BOraid_delete = t.ajaxDeleteRaid;
    uW.r8x6Home = t.butSendHome;
    uW.pr57Recall = t.butRecall2;
  
    var atkclass='';
    if(Seed && Seed.queue_atkinc) {
      for(k in Seed.queue_atkinc){
        m = Seed.queue_atkinc[k];
        if (m.marchType == 4){
    	   atkclass = 'style="background-color:#FF9999;"';
    	 }
      }
    }
    
    t.cont.innerHTML = '<TABLE class=ptTab align=center><TR><TD><INPUT class=bopbSubtab ID=BoptmrchSubM type=submit value="'+ uW.g_js_strings.commonstr.marching +'"></td>\
          <TD><INPUT class=bopbSubtab ID=BoptmrchSubA type=submit '+atkclass+' value="' + uW.g_js_strings.modaltitles.impatks + '"></td>\
          <TD><INPUT class=bopbSubtab ID=BoptmrchSubR type=submit value="'+uW.g_js_strings.openEmbassy.encampall+'"></td>\
          <TD><INPUT class=bopbSubtab ID=BoptmrchSubZ type=submit value="'+uW.g_js_strings.commonstr.reinforced+'"></td><td><input type=button value="?" id=boaidemarches class=boAide></td></tr></table>\
      <DIV id="BoptMarchOutput" style="margin-top:5px; height:'+(Options.HauteurBoite-65)+'px;max-height:'+(Options.HauteurBoite-65)+'px;overflow-y:auto"></div>';
     t.marchDiv = ById('BoptMarchOutput'); 
    ById('BoptmrchSubA').addEventListener('click', e_butSubtab, false);
    ById('BoptmrchSubR').addEventListener('click', e_butSubtab, false);
    ById('BoptmrchSubM').addEventListener('click', e_butSubtab, false);
    ById('BoptmrchSubZ').addEventListener('click', e_butSubtab, false);
       ById('boaidemarches').addEventListener('click', function(){
    	       	 window.open(sitesupport+"?page=aide_marches");
    	} , false);
       if (atkclass!='') {
       changeSubtab (ById('BoptmrchSubA'));  
       }else {
       changeSubtab (ById('BoptmrchSubM'));  
       }
       
      function e_butSubtab (evt){
          changeSubtab (evt.target);   
      }
    
      function changeSubtab (but){
          if (but == t.curTabBut)
            return;
          if (t.curTabBut){
            t.curTabBut.className='bopbSubtab'; 
            t.curTabBut.disabled=false;
          }
          t.curTabBut = but;
          but.className='bopbSubtab bopbSubtabSel'; 
          but.disabled=true;
          t.curTabName = but.id.substr(11);
          if (Options.currentTab=="Marches") t.show2();
      }  
    
  },
  show2 : function (){
    var t = Tabs.Marches;
    t.state = null;
    clearTimeout (t.displayTimer);
    if (t.curTabName == 'Z')
      t.showReinforcementsOut();
    else if (t.curTabName == 'R')
      t.showReinforcements();
    else if (t.curTabName == 'M')
      t.showMarches(9);
    else
      t.showAttacks();
  },
 
   /***   ATTACKS SUBTAB  ***/
  showAttacks : function (){
      var t = Tabs.Marches;
      clearTimeout (t.displayTimer);
      var now = unixTime();
      var target, atkType, who, atkclass;
      var ss = '<div class=boStat>'+uW.g_js_strings.modaltitles.impatks.toUpperCase()+' - <input type=button value="?" id=boaidemarches2 class=boAide></div>';
      var s = '';
      s += '<STYLE> .eclkk{background:#ffff55;} .attackkk{background:#ff5555;} .attackkA{background:#ff9955;}</style>';
      s += '<TABLE border=0 cellspacing=0 cellpadding=2 width=100% class=ptTab>';
      s += '<tr><td width=55><b>'+uW.g_js_strings.commonstr.timeremaining+'</td><td width=60><b>Def</td><td width=140 colspan=2><b>'+uW.g_js_strings.commonstr.location+'</td><td width=150 colspan=2><b>'+uW.g_js_strings.commonstr.attacker+'</td><td width=35><b>'+uW.g_js_strings.commonstr.distance+'</td><td width=25><b>'+uW.g_js_strings.commonstr.knight+'</td><td><b>'+uW.g_js_strings.commonstr.troops+'</td></tr>';  
      var at=0;
      if(Seed && Seed.queue_atkinc) {
       var sortem = [];    
       for (var k in Seed.queue_atkinc) 
          sortem.push (Seed.queue_atkinc[k]);

        sortem.sort (function (a,b){
          var x; if ((x = a.arrivalTime-b.arrivalTime)!=0) 
            return x; 
          return b.arrivalTime-a.arrivalTime;
        });    

       for (i=0; i<sortem.length; i++){
          var m = sortem[i]; 
      
      	if (m.marchType == 3){
	      atkType = uW.g_js_strings.commonstr.scouting;
	      atkclass = 'eclkk';
	    } else if (m.marchType == 4){
	      atkType = uW.g_js_strings.commonstr.atk;
	      atkclass = 'attackkk';
	       var nbtroupe=0;
	       for (k in m.unts){
	                nbtroupe += parseInt(m.unts[k]);
                }
	        if (nbtroupe==1) {
	         atkclass = 'attackkA';
	        }
	      
	    } else {
	      atkType ="?";
	      atkclass = '';
    	 }
    	 if (atkclass !='') {  
    	 at++;
    	 s += '<tr align=left class="'+atkclass+'">';
    	 var arrivedans = unsafeWindow.timestr(parseInt(m.arrivalTime - unixTime()));
    	 s += '<td class="'+atkclass+'">' + arrivedans +'</td>';
    	 var couelur="";
    	 var city = Cities.byID[m.toCityId];
    	 if (city.tileId == m.toTileId) {
           target = '<a onclick="citysel_click(document.getElementById(\'citysel_'+ (city.idx+1)+'\'));">'+ city.name.substring(0,10) +'</a>';
           cityID = 'city'+ m.toCityId;
	   Gate = parseInt(Seed.citystats[cityID].gate);
	   if(Gate == 0) {
	   	bouttt = '<input type=button value="DEF OFF" id="but_'+m.toCityId+'" style="background-color:#00AA00;padding:2px;border:1px solid yellow;">';
	   	}	   else {
		bouttt = '<input type=button value="DEF ON" id="but_'+m.toCityId+'" style="background-color:red;">';
		}
           coordos = '<a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">('+ city.x + ',' + city.y +')</a>';
         } else {
           target = 'TS';
           bouttt='';
           for (k in Seed.wilderness['city'+m.toCityId]){
            if (Seed.wilderness['city'+m.toCityId][k].tileId == m.toTileId){
             coordos = '<a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">('+Seed.wilderness['city'+m.toCityId][k].xCoord + ',' + Seed.wilderness['city'+m.toCityId][k].yCoord+')</a>';
             break;           
            }
           }
         }  
         s += '<td class="'+atkclass+'" align=center>'+bouttt+'</td><td class="'+atkclass+'" align=center><b>' + target + '<td class="'+atkclass+'" align=center>'+coordos+'</b></td>';
         
         if (Seed.players['u'+m.pid]) {
	    who = '<span>'+Seed.players['u'+m.pid].n +'<br>'+addCommas(Seed.players['u'+m.pid].m)+'</span>';
	 
	 } else if (m.players && m.players['u'+m.pid]) {
	    who = m.players['u'+m.pid].n;
	 } else{
	    who = 'Inconnu';
	
      	 }
      	 if (m.fromXCoord) { 
      	  who += '</td><td class="'+atkclass+'"><a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">(' + m.fromXCoord +','+ m.fromYCoord+')</a>';
      	 } else {
      	  who += '</td><td class="'+atkclass+'">???</a></td>';
      	 }
      	 s += '<td class="'+atkclass+'">' + who + '</td>';
      	 if (m.fromXCoord) {
      	  s +='<td class="'+atkclass+'">'+ distance(city.x,city.y,m.fromXCoord,m.fromYCoord) +'</td>';
      	 } else {
      	   s +='<td class="'+atkclass+'">&nbsp;</td>';
      	 }
         var troupe = "";
         for (k in m.unts){
          var uid = parseInt(k.substr (1));
          troupe += m.unts[k] +' '+ unsafeWindow.unitcost['unt'+uid][0] +'<br>';
         }
         var knh='&nbsp;';
         if (m.knt) {
	  for (k in m.knt){
	    knh=parseInt(m.knt[k]);
	  }        
         }
	 s += '<td class="'+atkclass+'">'+knh+'</td>';
         s += '<td class="'+atkclass+'">' + troupe +'</td>';
 
         s += '</tr>';
         } 
      	} 
      	s+='</table>';
      	if (at==0) {
      	 s ="<tr><colspan=4><br><center>"+uW.g_js_strings.ImpendingAttacks.noIncomingAttacks+"...</td></tr>";
      	}
      }
      t.marchDiv.innerHTML = ss + "" + s; 
       ById('boaidemarches2').addEventListener('click', function(){
          	       	 window.open(sitesupport+"?page=aide_marches2");
    	} , false);
       for (var cityId in Cities.byID){
      	var but = document.getElementById ('but_'+ cityId);
      	if (but) addListener (but, cityId);
       }
       function addListener (but, i){      	 but.addEventListener ('click', function (){t.butToggleDefMode(i)}, false);       }
      
      t.displayTimer = setTimeout (t.showAttacks, 900);
    },
    defMode:{},
    butToggleDefMode : function (cityId){
        var t = Tabs.Marches;
        var mode = 1;
        if (Seed.citystats["city" + cityId].gate != 0)
          mode = 0;
          t.ajaxSetDefMode (cityId, mode, function (newMode){
    
          });
    },
    ajaxSetDefMode : function (cityId, state, notify){
    		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    		params.cid = cityId;
    		params.state = state;
    		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/gate.php" + unsafeWindow.g_ajaxsuffix, {
    			method: "post",
    			parameters: params,
    			onSuccess: function (rslt) {
    				if (rslt.ok) {
    					Seed.citystats["city" + cityId].gate = state;
    					notify (state);
    				} 
    			},
    			onFailure: function () {
    			}
    		})
     },
    
    /***   MARCHES SUBTAB  ***/
    showMarches : function (numville){
 
      var t = Tabs.Marches;
      var rownum = 0;
      var now = unixTime();
      var names = ['Ravi', 'Mili', 'Eclai', 'Piqu', 'Pala', 'Arch', 'Cav', 'CavL', 'Wago', 'Bali', 'Beli', 'Cata'];
      clearTimeout (t.displayTimer);
      if (t.state == null){       
       var s = '<div class=boStat>'+uW.g_js_strings.modal_openRallypoint.troopmove+' ('+uW.g_js_strings.commonstr.remove+' Raid :<input id=BOVoirRaid type=checkbox '+ (!Options.voirRaid?'':' CHECKED ') +'>) - <input type=button value="?" id=boaidemarches1 class=boAide></div>';  
       s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;}</style><input style="font-size:12px" type=button id="9_BOVilleBouton" value="0">';
       for (var c=0; c<Cities.numCities; c++){
            s += '<input style="font-size:12px" type=button id="'+ c +'_BOVilleBouton" value="' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name.substring(0,10) +'">';
       }
       s += '<div id="showMarchDiv"></div>';
       t.marchDiv.innerHTML = s;
        ById('boaidemarches1').addEventListener('click', function(){
           	       	 window.open(sitesupport+"?page=aide_marches1");
    	} , false);
       ById('BOVoirRaid').addEventListener('click', function() {
       
         Options.voirRaid = ById('BOVoirRaid').checked;
         saveOptions();
         
       }, false);
       
       ById("9_BOVilleBouton").addEventListener('click', function(){
                           var t = Tabs.Marches;
                           clearTimeout (t.displayTimer);
                           t.showMarches(this.id.substring(0,1));
                           
       }, false);
       
       for (var c=0; c<Cities.numCities; c++){
          ById(c + "_BOVilleBouton").addEventListener('click', function(){
                    var t = Tabs.Marches;
                    clearTimeout (t.displayTimer);
                    t.showMarches(this.id.substring(0,1));
           }, false);
       }
       t.state = 1; 
      }
      s = '<TABLE cellspacing=0 cellpadding=2 width=100% class=ptTab>';
      tot = [];
      for (i=0; i<13; i++)  tot[i] = 0;
      var c = numville;
      if (numville==9) {
        for (var c=0; c<Cities.numCities; c++){
          var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
               
          if (matTypeof(que)=='object') {
            var a=0;
            for (k in que) {
              march = que[k]; 
              if ((march.marchType!=2 && !Options.voirRaid) || (march.marchType!=9 && march.marchType!=2 && Options.voirRaid) ) { 
                 a++;
                 if (a==1) {
      	             var cityID = 'city'+ Cities.cities[c].id;
      	             var slots=0;
		     for(var z in Seed.queue_atkp[cityID])
		     	slots++;      
      	             var niveauPointRall=parseInt(getCityBuilding (Cities.cities[c].id, 12).maxLevel); 
      	             if (niveauPointRall==12) niveauPointRall=11;  
      	  	     s+= '<TR class="city"><TD class="city">PR : '+slots+' / '+niveauPointRall+'</td><TD class="city" colspan=19 align=center><font size=3><B><i><u>'+uW.g_js_strings.commonstr.city+' ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
      	         }
                 var mid = k.substr(1);
                 knight = '';
                 if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
		  for (i in Seed.knights['city'+ Cities.cities[c].id]) {
		    if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +'';
		  }
  		 } else knight = '';
                var playerId = march.toPlayerId;
                if (playerId==undefined) playerId=0;
                var cityId = march.toCityId;
                var tileType = parseInt(march.toTileType);
                var tileLevel = march.toTileLevel;
                var who = 'Inconnu';
                if (Seed.players['u' + playerId]) {
		 who = Seed.players['u' + playerId].n;
		}
		if (march.marchType==1) { 
		  var player = "<span>"+uW.g_js_strings.commonstr.city+" "+ tileLevel +"</span>";
		}else {
		  var player = "<span title='F5 et cela corrige le pb'>Barb "+ tileLevel +"</span>";
		}
		if (march.marchType==10 || march.marchType==11) { 
		  var player = "<span>F.S. "+ tileLevel +"</span>";
		}
		var tileNames = [uW.g_js_strings.commonstr.barbarians, uW.g_js_strings.commonstr.grassland, uW.g_js_strings.commonstr.lake, uW.g_js_strings.commonstr.woods, uW.g_js_strings.commonstr.hills, uW.g_js_strings.commonstr.mountain, uW.g_js_strings.commonstr.plain, uW.g_js_strings.commonstr.city, uW.g_js_strings.commonstr.darkForest];
		var numtile=parseInt(tileType/10) + 1;
		if (tileType==10) numtile=1;
		if (tileType==11) numtile=2;
                if (tileType <= 50) { 
                  player = tileNames[numtile] +" " + tileLevel;
                }
                if (tileType == 51 && playerId == 0 && march.toTileLevel==7) { 
                  player = uW.g_js_strings.commonstr.city+" " + tileLevel;
                }
                if (tileType == 51 && playerId == 0 && march.toTileLevel==9) {
		  player = "Barb " + tileLevel;
                }
                if (tileType == 54 && playerId == 0) {
		     player = "F.S. " + tileLevel;
                }
                var nomville="";
                if (playerId > 0 && tileType == 51) { 
                 if (march.marchType==1) {
                  for(i=0; i<Cities.numCities; i++) {
                   if (cityId==Cities.cities[i].id) {
                    nomville=Cities.cities[i].name
                     break;
                   }
                  }
                  player = 'Votre ville '+ nomville;
                 } else {
                  player = 'Ville Niv ' + tileLevel;
                 }
                }
                var typeattack="?";
                if (march.marchType==3) typeattack=uW.g_js_strings.commonstr.scouting; 
                if (march.marchType==4) typeattack=uW.g_js_strings.modal_barracks_train.attack;
                if (march.marchType==10) typeattack=uW.g_js_strings.modal_barracks_train.attack;
                if (march.marchType==11) typeattack=uW.g_js_strings.commonstr.scouting;
                if (march.marchType==1) typeattack=uW.g_js_strings.commonstr.transporting;
                if (march.marchType==5) typeattack=uW.g_js_strings.commonstr.reassign;
                if (march.marchType==9) typeattack=uW.g_js_strings.modal_barracks_train.attack + ' Raid';
                var now = new Date();
                var statusm = march.marchStatus;
                var Marchstatut="<span title='Type : "+march.marchType+" "+uW.g_js_strings.commonstr.status+" : "+statusm+"'>?</span> ";
                var arrivedans="0s";
                var arrivedanssec=0;
		if (statusm==1) { 
		 Marchstatut="";
		 if (march.marchType==3 || march.marchType==11) 
		  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/scouting.jpg" align=absmiddle>';
		 if (march.marchType==4 || march.marchType==10) 
		  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/attacking.jpg" align=absmiddle>';
		 if (march.marchType==9) 
		  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/attacking.jpg" align=absmiddle>';
		 if (march.marchType==1) 
		  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/transporting.jpg" align=absmiddle>';
                 if (march.marchType==5) 
                  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>';
		  Marchstatut+="&nbsp;"+uW.g_js_strings.commonstr.marching; 
		  arrivedans = unsafeWindow.timestr(parseInt(march.destinationUnixTime - unixTime()));
		  arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
		}
                if (statusm==8) { 
                  Marchstatut = '<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/returning.jpg" align=absmiddle>&nbsp;'+uW.g_js_strings.commonstr.back;
                  arrivedans = unsafeWindow.timestr(march.returnUnixTime - unixTime());
                  arrivedanssec = parseInt(march.returnUnixTime - unixTime());
                }
                if (statusm==2) { 
                   Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>&nbsp;'+uW.g_js_strings.commonstr.encamped;
                }
                if (statusm==5) { 
                   Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>&nbsp;'+uW.g_js_strings.attack_generatequeue.waitreport;
                }
                if (statusm==4) { 
		   Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/autoAttack/raid_resting.png" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.unloadingloot;
                }
                if (statusm==3 || statusm==10 ) { 
		  Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/autoAttack/raid_stopped_desat.png" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.raidstopped;
		}
 
                s += '<TR align=left><td align=left width=10%>';
                if (march.marchType!=9 && statusm==1 && arrivedanssec>60) s +='<A class=button20 onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')"><SPAN>'+uW.g_js_strings.commonstr.recall+'</span></a>';
                if (march.marchType!=9 && statusm==2) s +='<A class=button20 onclick="attack_recall('+ mid+', 1, '+Cities.cities[c].id+');"><span>'+uW.g_js_strings.commonstr.recall+'</span></a>';
                if (march.marchType==9 && statusm==10 && arrivedanssec<=0) s +='<A class=button20 onclick="BOraid_delete('+ mid+','+Cities.cities[c].id+');return false;"><span>'+uW.g_js_strings.commonstr.remove+'</span></a>';
             
             s +='</td><td align=left width=10%>'+typeattack+'</td><td>'+arrivedans+'</td><td align=left width=15%>' + Marchstatut +'</td>\
                <TD align=left width=15%>' + player + '</td><td><a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a></td><td>' + knight +' </td><td colspan=12>'
	       for (i=1; i<13; i++) {
	                  if (statusm==8) { 
	                    if (parseInt (march['unit'+ i +'Return']) > 0) {
	      	           s += unsafeWindow.unitcost['unt'+i][0].substr(0,6)+" :" + parseInt (march['unit'+ i +'Return']) + "<br>";
	      	          tot[i] += parseInt (march['unit'+ i +'Return']);
	                  }
	                  
	                  } else {
	                   if (parseInt (march['unit'+ i +'Count']) > 0) {
	                       s += unsafeWindow.unitcost['unt'+ i][0].substr(0,6) +" :" + parseInt (march['unit'+ i +'Count']) + "<br>";
	                       tot[i] += parseInt (march['unit'+ i +'Count']);
	                   }
	                  }
                }
	      
                s += '</td><td style="font-size:11px">';
      		if (march.marchType!=9) {
      		  s += '<a  class=button20 onclick="view_march('+ mid+');return false;";><span>'+uW.g_js_strings.commonstr.view+'</psan></a></td>';
      		  }else {
      		  s+='</td>';
      		  }
                s += '</tr>';
              }
            }
        }
      }
      s += '<TR><TD colspan=20><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100%><tr><td colspan=1></td>';
     	 for (var k=1;k<13;k++)
     	 	s += '<TD width=7% align=center><B>' + unsafeWindow.unitcost['unt'+k][0].substr(0,6) + '</b></td>';
     	 s += '</tr>';
     	 s += '<TR align=center><TD class="tot" align=left width=10%><B>TOTAUX</b></td>';
     	 for (i=1; i<13; i++)
     		s+= '<TD class="tot">'+ tot[i] +'</td>';
     	 s += '<td></td></tr></table>';
	 s += '<BR><BR><DIV style="font-size: 10px"></div>';
            
  } else { 
      
      
   var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
   if (matTypeof(que)=='object') {      
			var a=0;
			for (k in que){
	                   march = que[k]; 
	                   
	              if ((march.marchType!=2 && !Options.voirRaid) || (march.marchType!=9 && march.marchType!=2 && Options.voirRaid) ) { /// Marche Type \\ 2= DÃ©fense / 3= Eclaireur / 4= Attaque
                  a++;
	                   if (a==1) {
	         	             var cityID = 'city'+ Cities.cities[c].id;
	         	             var slots=0;
	   		     for(var z in Seed.queue_atkp[cityID])
	   		     	slots++;
	   	      	             
	         	             var niveauPointRall=parseInt(getCityBuilding (Cities.cities[c].id, 12).maxLevel); // 12=Point de ralliement
	        if (niveauPointRall==12) niveauPointRall=11;  // fix : Send eleven armies at a time for level 12
	         	  	     s+= '<TR class="city"><TD class="city">PR : '+slots+' / '+niveauPointRall+'</td><TD class="city" colspan=18 align=center><font size=3><B><i><u>'+unsafeWindow.g_js_strings.commonstr.city+' ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
	         	        }
	                   var mid = k.substr(1);
	                   knight = '';
	                    if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
	   		  				    	for (i in Seed.knights['city'+ Cities.cities[c].id]) {
	   		  				    			if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '&nbsp;(Chev : ' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +')';
	   		  				    	}
	     				    } else knight = '';
	                  var playerId = march.toPlayerId;
			                 if (playerId==undefined) playerId=0;
			                 var cityId = march.toCityId;
			                 var tileType = parseInt(march.toTileType);
			                 var tileLevel = march.toTileLevel;
			                 var who = 'Inconnu';
			                 if (Seed.players['u' + playerId]) {
			 		 who = Seed.players['u' + playerId].n;
			 		}
			 		if (march.marchType==1) { // si transport c'est forcement sur une ville lol
			 		  var player = "<span>Ville Niv "+ tileLevel +"</span>";
			 		}else {
			 		  var player = "<span title='Le jeu Bug !! Chier - F5 et cela corrige le pb....'>Barb Niv "+ tileLevel +"</span>";
			 		}
			 		if (march.marchType==10 || march.marchType==11) { 
			 		  var player = "<span>F.S. Niv "+ tileLevel +"</span>";
			 		}
			 		var tileNames = ['Barbares', 'Prairie', 'Lac', 'Bois', 'Collines', 'Montagne', 'Plaine', 'Ville', 'FS'];
			 		var numtile=parseInt(tileType/10) + 1;
			 		if (tileType==10) numtile=1;
			 		if (tileType==11) numtile=2;
			                 if (tileType <= 50) { // TS
			                   player = tileNames[numtile] +" Niv " + tileLevel;
			                 }
			                 if (tileType == 51 && playerId == 0 && march.toTileLevel==7) { // Ville
			                   player = "Ville Niv " + tileLevel;
			                 }
			                 if (tileType == 51 && playerId == 0 && march.toTileLevel==9) { // Barbares
			 		  player = "Barb Niv " + tileLevel;
			                 }
			                 if (tileType == 54 && playerId == 0) { // Barbares
			 		     player = "F.S. Niv " + tileLevel;
			                 }
			                 var nomville="";
			                 if (playerId > 0 && tileType == 51) { // ville
			                  if (march.marchType==1) {
			                   for(i=0; i<Cities.numCities; i++) {
			                    if (cityId==Cities.cities[i].id) {
			                     nomville=Cities.cities[i].name
			                      break;
			                    }
			                   }
			                   player = 'Votre ville '+ nomville;
			                  } else {
			                   player = 'Ville Niv ' + tileLevel;
			                  }
			                 }
                var typeattack="?";
	             if (march.marchType==3) typeattack='Eclaireur';
	                 if (march.marchType==4) typeattack='Attaque';
	                 if (march.marchType==10) typeattack='Attaque';
	                 if (march.marchType==11) typeattack='Eclaireur';
	                 if (march.marchType==1) typeattack='Transport';
	                 if (march.marchType==5) typeattack='R&eacute;assigne';
                if (march.marchType==9) typeattack='Raid attaque';
	                 var now = new Date();
                var statusm = march.marchStatus;
                var Marchstatut="<span title='type : "+march.marchType+" Status : "+statusm+"'>?</span> ";
                var arrivedans="0s";
                var arrivedanssec=0;
		if (statusm==1) { 
		 Marchstatut="";
		 if (march.marchType==3 || march.marchType==11) 
		  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/scouting.jpg" align=absmiddle>';
		 if (march.marchType==4 || march.marchType==10) 
		  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/attacking.jpg" align=absmiddle>';
		 if (march.marchType==9) 
		  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/attacking.jpg" align=absmiddle>';
		 if (march.marchType==1) 
		  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/transporting.jpg" align=absmiddle>';
                 if (march.marchType==5) 
                  Marchstatut+='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>';
		  Marchstatut+="&nbsp;"+uW.g_js_strings.commonstr.marching; 
		  arrivedans = unsafeWindow.timestr(parseInt(march.destinationUnixTime - unixTime()));
		  arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
		}
                if (statusm==8) { 
                  Marchstatut = '<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/returning.jpg" align=absmiddle>&nbsp;Retour';
                  arrivedans = unsafeWindow.timestr(march.returnUnixTime - unixTime());
                  arrivedanssec = parseInt(march.returnUnixTime - unixTime());
                }
                if (statusm==2) { 
                   Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>&nbsp;Campement';
                }
                if (statusm==5) { 
                   Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>&nbsp;Rapport';
                }
                if (statusm==4) { 
		   Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/autoAttack/raid_resting.png" align=absmiddle>&nbsp;D&eacute;chargement';
                }
                if (statusm==3 || statusm==10) { 
		  Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/autoAttack/raid_stopped_desat.png" align=absmiddle>&nbsp;Arret&eacute;e';
		}
 
                s += '<TR align=left><td align=left width=10%>';
                if (march.marchType!=9 && statusm==1 && arrivedanssec>60) s +='<A class=button20 onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')"><SPAN>Rappeler</span></a>';
                if (march.marchType!=9 && statusm==2) s +='<A class=button20 onclick="attack_recall('+ mid+', 1, '+Cities.cities[c].id+');"><span>Rappeler</span></a>';
                if (march.marchType==9 && statusm==10 && arrivedanssec<=0) s +='<A class=button20 onclick="BOraid_delete('+ mid+','+Cities.cities[c].id+');return false;"><span>Supprimer</span></a>';
             
               s +='</td><td align=left width=10%>'+typeattack+'</td><td>'+arrivedans+'</td><td align=left width=15%>' + Marchstatut +'</td>\
	                      <TD align=left width=15%>' + player + '</td><td><a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a></td><td>' + knight +' </td><td colspan=12>'
	      	       for (i=1; i<13; i++) {
	      	                  if (statusm==8) { 
	      	                    if (parseInt (march['unit'+ i +'Return']) > 0) {
	      	      	           s += names[i-1]+" :" + parseInt (march['unit'+ i +'Return']) + "<br>";
	      	      	          tot[i] += parseInt (march['unit'+ i +'Return']);
	      	                  }
	      	                  
	      	                  } else {
	      	                   if (parseInt (march['unit'+ i +'Count']) > 0) {
	      	                       s += names[i-1]+" :" + parseInt (march['unit'+ i +'Count']) + "<br>";
	      	                       tot[i] += parseInt (march['unit'+ i +'Count']);
	      	                   }
	      	                  }
	                      }
	      	      
	                      s += '</td><td style="font-size:11px">';
	            		if (march.marchType!=9) {
	            		  s += '<a  class=button20 onclick="view_march('+ mid+');return false;";><span>D&eacute;tail</psan></a></td>';
	            		  }else {
	            		  s+='</td>';
	            		  }
                s += '</tr>';
	        }// fin de MarchType
     } // fin k in que
     s += '<TR><TD colspan=18><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100% class=ptTab ><tr><td colspan=1></td>';
     for (k=0; k<names.length; k++)  s += '<TD width=7% align=center><B>' + names[k] + '</b></td>';
     s += '</tr>';
     s += '<TR align=center><TD class="tot" align=left width=10%><B>TOTAUX</b></td>';
     for (i=1; i<13; i++) s+= '<TD class="tot">'+ tot[i] +'</td>';
     s += '<td></td></tr></table>';
    } else {
     s= '<br>Aucune marche en cours...';
    } 
   } // Fin c=99
   ById('showMarchDiv').innerHTML = s;
   t.displayTimer = setTimeout (function() { t.showMarches(numville);   }, 1000);
  },
  ajaxDeleteRaid: function(marchId, cityId) {
      var villeencours=cityId;
               var march = Seed.queue_atkp["city" + villeencours]["m" + marchId];
               if (march == null){
                            return;
               }    
               var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
               params.action="deleteMarch";
               params.marchId = marchId;
           params.ctrl="BotManager";
           params.settings={cityId:villeencours}; 
      	   unsafeWindow.ajax.Request(unsafeWindow.g_ajaxpath+"ajax/_dispatch.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
onSuccess:function(transport) {
  var m = eval("(" + transport.responseText + ")");
   if (m.ok){        
            var j=marchId;
            var t=cityId;
            var n=Seed.units["city"+t];
            for(var o=0;o<13;++o){
             if (m["unit"+o+"Return"]) {
              var p=parseInt(m["unit"+o+"Return"]);
              if(!isNaN(p)&&(p>0)){
               n["unt"+o]=parseInt(n["unt"+o])+p;
               }
             }
            }
            unsafeWindow.cityinfo_army();
            var s="city"+t;
            // recherche de mon chevalier
            var mymarch = unsafeWindow.seed.queue_atkp["city" + t]["m" + j];
            var kngId= mymarch.knightId;
            delete Seed.queue_atkp[s]["m"+j];
            if(unsafeWindow.Object.keys(Seed.queue_atkp[s]).length==0){
              Seed.queue_atkp[s]=[];
            }
            Seed.knights["city"+t]["knt"+kngId].knightStatus=1;          
     } else {

       
     }
    }, onFailure: function () {
       
    },
   });

  },
  /***  REINFORCEMENTS SUBTAB  ***/
  showReinforcementsOut : function (){
      var rownum = 0;
      var names = ['Ravi', 'Mili', 'Eclai', 'Piqu', 'Pala', 'Arch', 'Cav', 'CavL', 'Wago', 'Bali', 'Beli', 'Cata'];
      var t = Tabs.Marches;
      clearTimeout (t.displayTimer);
      var s = '<div class=boStat>Liste des troupes envoy&eacute;es en renforts - <input type=button value="?" id=boaidemarches4 class=boAide></div>';
      s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;}</style>';
      s += '<TABLE cellspacing=0 cellpadding=2 width=100% class=ptTab >';
      tot = [];
      for (i=0; i<13; i++)
        tot[i] = 0;
        
      for (var c=0; c<Cities.numCities; c++){
        var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
        if (matTypeof(que)=='array')
          continue;

        var a=0;
        for (k in que){
          march = que[k]; 
          if (march.marchType==2) { 
          a++;
          if (a==1) {
	   s+= '<TR class="city"><TD class="city" colspan=16 align=left><B>'+unsafeWindow.g_js_strings.commonstr.city+' ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
          }
          var mid = k.substr(1);
          knight = '';
	  if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
	  		  for (i in Seed.knights['city'+ Cities.cities[c].id]) {
	  		    if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +'';
	  		  }
  	  } else knight = '';
          if (parseInt(march.knightCombat)>0) knight=' ('+ march.knightCombat +')';
	  try {
	     player = Seed.players['u'+march.toPlayerId].n; //Seed.players['u'+k].n;
	   } catch (err){
	     player = 'Inconnu';
          }
        
          s += '<TR align=left><td align=left width=12%>';
          var statusm = march.marchStatus;
          var Marchstatut='';
          var arrivedans="0s";
          var arrivedanssec=0;
          if (statusm==1) { 
            Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>&nbsp;'+uW.g_js_strings.commonstr.marching;
            arrivedans = unsafeWindow.timestr(parseInt(march.destinationUnixTime - unixTime()));
            arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
          }
          if (statusm==2) { 
            Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>&nbsp;Campement';
          }
          if (statusm==8) { 
            Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/returning.jpg" align=absmiddle>&nbsp;Retour';
            arrivedans = unsafeWindow.timestr(parseInt(march.returnUnixTime - unixTime())); 
            arrivedanssec = parseInt(march.returnUnixTime - unixTime());
          }
          if (statusm==5) { 
           Marchstatut='<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/reinforce.jpg" align=absmiddle>&nbsp;En attente Rapport';
          }
          if (statusm==1 && arrivedanssec>60){
            s +='<A class=button20 onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')"><SPAN>Rappeler</span></a>';
          }
          if (statusm==2) { 
             s +='<A class=button20 onclick="pr57Recall('+ mid+')"><SPAN>Rappeler</span></a>';
          } else {
            s += '&nbsp;';
          }
             
          s+='</td><td align=left width=15%>'+Marchstatut+'</td><td>'+arrivedans+'</td><TD align=left width=30%>' + player + ' <a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a>&nbsp;' + knight +' </td><td colspan=12>'
          for (i=1; i<13; i++) {
            if (statusm==8) { 
              if (parseInt (march['unit'+ i +'Return']) > 0) {
	          s += " " + parseInt (march['unit'+ i +'Return']) + " "+names[i-1]+"<br>";
	          tot[i] += parseInt (march['unit'+ i +'Return']);
            }
            
            } else {
             if (parseInt (march['unit'+ i +'Count']) > 0) {
                s += " " + parseInt (march['unit'+ i +'Count']) + " "+names[i-1]+"<br>";
                tot[i] += parseInt (march['unit'+ i +'Count']);
             }
            }
          }
          s += '</td></tr>';
          }// fin de MarchType
        }      
      } 
      
       s += '<TR><TD colspan=16><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 class=ptTab width=100%><tr><td colspan=1></td>';
            for (k=0; k<names.length; k++)
              s += '<TD width=7% align=center><B>' + names[k] + '</b></td>';
            s += '</tr>';
            s += '<TR align=center><TD class="tot" align=left width=10%><B>TOTAUX</b></td>';
            for (i=1; i<13; i++)
              s+= '<TD class="tot">'+ tot[i] +'</td>';
      s += '</tr></table>';
      t.marchDiv.innerHTML = s;
        ById('boaidemarches4').addEventListener('click', function(){
          	       	 window.open(sitesupport+"?page=aide_marches4");
    	} , false);
      t.displayTimer = setTimeout (t.showReinforcementsOut, 5000);
      return;
  },
     
  showReinforcements : function (){
   var rownum = 0;
    var names = ['Ravi', 'Mili', 'Eclai', 'Piqu', 'Pala', 'Arch', 'Cav', 'CavL', 'Wago', 'Bali', 'Beli', 'Cata'];
    var t = Tabs.Marches;
    clearTimeout (t.displayTimer);
      
    function clickShowRemaining (){
      checkBox = ById('idCheck2');
      if (checkBox.checked)
        Options.encRemaining = false;
      else
        Options.encRemaining = true;
      t.show2 ();
    }
  
    enc = {};
    numSlots = 0;
    
    if (matTypeof(Seed.queue_atkinc) != 'array'){
      for (k in Seed.queue_atkinc){
        march = Seed.queue_atkinc[k];
        if (march.marchType == 2){
          ++numSlots;
          city = march.toCityId;
          from = march.fromPlayerId;
          if (!enc[city])
            enc[city] = {};
          if (!enc[city][from])
            enc[city][from] = [];
          s = {};
          s.knight = parseInt (march.knightCombat);
          s.marchId = k.substr(1);
          s.fromXCoord = march.fromXCoord;
          s.fromYCoord = march.fromYCoord;
          s.troops = [];
          for (i=1; i<13; i++){
            if (Options.encRemaining)
              s.troops[i] = parseInt (march['unit'+ i +'Return']);
            else
              s.troops[i] = parseInt (march['unit'+ i +'Count']);
          }
          enc[city][from].push (s);
        }
      }
    }
    s = '<div class=boStat>Liste des troupes en renfort dans vos ambassades - <input type=button value="?" id=boaidemarches3 class=boAide></div>';
    if (numSlots == 0){
      s += '<BR><CENTER><B>Aucunes troupes en renfort actuellement.</b></center>';
    } else {
      s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;} .entete{background:#efa9a9;}</style>';
      s += '<TABLE cellspacing=0 cellpadding=2 width=100%>\
      <tr><td class="entete">Actions</td><td class="entete">Coordonn&eacute;es</td><td class="entete">Envoy&eacute; par</td><td class="entete">Chevalier</td><td colspan=12 class="entete">Unit&eacute;s</td><td class="entete">Entretien</td></tr>';

      tot = [];
      totent= 0;
      for (i=0; i<13; i++) {
        tot[i] = 0;
        
      }
      for (c in Cities.cities){
        dest = Cities.cities[c].id;
        if (enc[dest]){
          s+= '<TR><TD class="city" colspan=17 align=left><B>'+unsafeWindow.g_js_strings.commonstr.city+' ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
          for (p in enc[dest]){
            try {
              player = Seed.players['u'+p].n;
            } catch (err){
              player = '???';
            }
            for (m=0; m<enc[dest][p].length; m++){
              var march = enc[dest][p][m];
              knight = '';
              if (march.knight > 0)
                knight = ' '+ march.knight +'';       
              s += '<TR align=left><td align=left width=12%><A class=button20 onclick="r8x6Home('+ march.marchId +')"><SPAN>Renvoyer</span></a></td>\
              <TD align=left><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+march.fromXCoord+','+march.fromYCoord+')'+'</a></td>\
              <TD align=left width=25%>'+ player +' </td><td align=left>'+ knight+'</td><td colspan=12>'
              var g=0;
              for (i=1; i<13; i++){
               if (march.troops[i] > 0) {
                s += ''+ march.troops[i]  +' '+ names[i-1]  +'<br>';
               }
               tot[i] += march.troops[i];
               g+=parseInt(march.troops[i])*parseInt(unsafeWindow.unitupkeeps[i]);
               
              }
              totent += g;
              s += '</td><td>';
              s += addCommas(g) + '</td></tr>';
            }
          }
        }
      }
      s += '<TR><TD colspan=17><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100%><tr><td colspan=1></td>';
      for (k=0; k<names.length; k++)
        s += '<TD width=7% align=center><B>' + names[k] + '</b></td>';
      s += '</tr>';
      s += '<TR align=center><TD class="tot" align=left width=10% rowspan=2><B>TOTAUX</b></td>';
      for (i=1; i<13; i++)
        s+= '<TD class="tot">'+ tot[i] +'</td>';
      s += '</tr><td colspan=12>Consommation : '+addCommas(totent)+' nourriture / h</td></table>';
    }

    s += '<BR><BR><INPUT type=CHECKBOX id=idCheck2 '+ (Options.encRemaining?'':' CHECKED ') +'> Show Original Troops';
    s += '<BR><BR><DIV style="font-size: 10px">NOTE : Vous devez rafraichir KOC pour voir les nouveaux renforts chez vous.</div>';
    t.marchDiv.innerHTML = s;
    checkBox = ById('idCheck2');
    ById('boaidemarches3').addEventListener('click', function(){  window.open(sitesupport+"?page=aide_marches3");    } , false);
    checkBox.addEventListener('click', clickShowRemaining, false);
    t.displayTimer = setTimeout (t.show2, 10000);
  },
  butSendHome : function (marchId){
        var t = Tabs.Marches;
        t.ajaxSendHome (marchId); 
   },
   ajaxSendHome : function (marchId, notify){ 
     var march = Seed.queue_atkinc['m'+ marchId];
     if (march == null)
         return; 
     var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
     params.mid = marchId;
     params.cid = march.toCityId;
     params.fromUid = march.fromPlayerId;
     params.fromCid = march.fromCityId;
     new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/kickoutReinforcements.php" + unsafeWindow.g_ajaxsuffix, {
         method: "post",
         parameters: params,
         onSuccess: function (rslt) {
           if (rslt.ok){
             var upkeep = 0;
             for (var i=1; i<13; i++)
               upkeep += parseInt(march["unit" + i + "Return"]) * parseInt(unsafeWindow.unitupkeeps[i]);
             unsafeWindow.seed.resources["city"+ march.toCityId].rec1[3] -= upkeep;
             if (parseInt(march.fromPlayerId) == parseInt(unsafeWindow.tvuid)) {
               var mymarch = unsafeWindow.seed.queue_atkp["city" + march.fromCityId]["m" + marchId];
               var marchtime = Math.abs(parseInt(mymarch.destinationUnixTime) - parseInt(mymarch.eventUnixTime));
               mymarch.returnUnixTime = unixTime() + marchtime;
               mymarch.marchStatus = 8;
             }
             delete unsafeWindow.seed.queue_atkinc["m" + marchId];
             if (notify != null)
               notify(null);
           } else {
             if (notify != null)
               notify(rslt.errorMsg);
           }
         },
         onFailure: function () {
           if (notify != null)
             notify(rslt.errorMsg);
         },
     });
  },
  butRecall2 : function (marchId){
     var t = Tabs.Marches;
     t.ajaxRecall2 (marchId); 
  },
  ajaxRecall2 : function (marchId, notify){
    var villeencours;
          for (var c=0; c<Cities.numCities; c++){
            var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
            if (matTypeof(que)=='array')
              continue;
            for (k in que){
              if (k == 'm'+marchId){
                villeencours = Cities.cities[c].id;
                break;
              }
            }    
        }  
     var march = Seed.queue_atkp["city" + villeencours]["m" + marchId];
           if (march == null){
             return;
           }    
           var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
           params.mid = marchId;
           params.cid = villeencours; 
           new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/undefend.php" + unsafeWindow.g_ajaxsuffix, {
               method: "post",
               parameters: params,
               onSuccess: function (rslt) {
                 if (rslt.ok){
                   if(rslt.updateSeed){
		   unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].marchStatus=8;
		   var marchtime=parseInt(unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].returnUnixTime)-parseInt(unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].destinationUnixTime);
		   var ut=unsafeWindow.unixtime();
		   if(unsafeWindow.seed.playerEffects.returnExpire>ut){marchtime*=0.5}
		   unsafeWindow.seed.queue_atkp["city"+villeencours]["m"+marchId].destinationUnixTime=rslt.destinationUnixTime||ut;
		   unsafeWindow.seed.queue_atkp["city"+villeencours]["m"+marchId].returnUnixTime=rslt.returnUnixTime||ut+marchtime*rslt.returnMultiplier;
		   unsafeWindow.seed.queue_atkp["city"+villeencours]["m"+marchId].marchStatus=8;
		   unsafeWindow.update_seed(rslt.updateSeed)
 		  }
 		 }
               },
               onFailure: function () {
               
               
               },
     });
          
  },   
  ajaxRecall : function (marchId, cid, notify){
       var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
              params.mid = marchId;
              params.cid = cid;
              
              new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelMarch.php" + unsafeWindow.g_ajaxsuffix, {
                  method: "post",
                  parameters: params,
                  onSuccess: function (rslt) {
                    if (rslt.ok){
                    
                     if(rslt.updateSeed){
 		       unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].marchStatus=8;   
 		       var marchtime=parseInt(unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].returnUnixTime)-parseInt(unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].destinationUnixTime);
 		       var ut=unsafeWindow.unixtime();
 		       if(unsafeWindow.seed.playerEffects.returnExpire>unsafeWindow.unixtime()){marchtime*=0.5}
		       unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId].destinationUnixTime=rslt.destinationUnixTime||ut;
		       unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId].returnUnixTime=rslt.returnUnixTime||ut+marchtime*rslt.returnMultiplier;
		       unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId].marchStatus=8;
 		       unsafeWindow.update_seed(rslt.updateSeed);
                     }
                     for(var j=1;j<13;j++){
		       unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId]["unit"+j+"Return"]=parseInt(unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId]["unit"+j+"Count"])
 		     }
 		    }
                  },
                  onFailure: function () {
                  
                  
                  },
     });

  },
};
Tabs.Search = {
  tabOrder: 4,
  tabLabel: uW.g_js_strings.commonstr.research,
  cont:null,
  state : null,
  show : function (div){
    var t = Tabs.Search;  
  },
  hide : function (){
  },
  clickedPlayerDetail : function (span, uid){
    var t = Tabs.AllianceList;
    span.onclick = '';
    span.innerHTML = "Recherche d&eacute;dails ...";
    t.fetchPlayerInfo (uid, function (r) {t.gotPlayerDetail(r, span)});
  },
  clickedPlayerLeaderboard : function (span, uid){
    var t = Tabs.AllianceList;
    span.onclick = '';
    span.innerHTML = "Recherche dans le tableau d'honneur ...";
    t.fetchLeaderboard (uid, function (r) {t.gotPlayerLeaderboard(r, span)});
  }, 
  gotPlayerLeaderboard : function (rslt, span){
    var t = Tabs.AllianceList;
    if (!rslt.ok){
      span.innerHTML = rslt.errorMsg;
      return;
    }
    if (rslt.totalResults == 0){
      span.innerHTML = "<B>Tableau d'honneur :</b> Pas trouv&eacute; ! (sous la brume ?)";
      return;
    }
    var p = rslt.results[0];
    var an = p.allianceName;
    if (!an || an=='' || p.officerType==4)
      an = 'Aucun';
    else
      an += ' ('+ officerId2String(p.officerType) +')';
    m = '<TABLE cellspacing=0 class=ptTab><TR><TD><B>Tableau Honneur : </b></td><TD colspan=2> '+uW.g_js_strings.commonstr.might+' : '+ p.might  +' &nbsp; Alliance : '+ an +'</td></tr>'; 
    for (var i=0; i<p.cities.length; i++){
      var c = p.cities[i];
      m += '<TR><TD align=right><B>'+unsafeWindow.g_js_strings.commonstr.city+' #'+ (i+1) +':</b></td><TD> &nbsp; '+ c.cityName 
      +' <a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ c.xCoord +',' +c.yCoord+ ')</a></td><TD width=75%> &nbsp; Niveau : '
      + c.tileLevel +' &nbsp; &nbsp; status: '+ cityStatusString (c.cityStatus) +' &nbsp; &nbsp; cr&eacute;de : ' + c.dateCreated.substr(0,10) +'</td></tr>';
    }  
    span.innerHTML = m + '</table>';
  },
  gotPlayerDetail : function (rslt, span){
    var t = Tabs.AllianceList;
    if (!rslt.ok){
      span.innerHTML = rslt.errorMsg;
      return;
    }
    var u = rslt.userInfo[0];
    var a = 'Aucun';
    if (u.allianceName)
      a = u.allianceName +' ('+ getDiplomacy(u.allianceId) + ')';
    var m = '<TABLE cellspacing=0 class=ptTab><TR><TD><B>D&eacute;dtails:</b> &nbsp; </td><TD>Alliance : '+ a +' &nbsp; Villes : '
          + u.cities +' &nbsp; Population : '+ u.population +'</td></tr><TR><TD></td><TD>Provinces : ';
    var pids = u.provinceIds.split (',');
    var p = [];
    for (var i=0; i<pids.length; i++)
      p.push(unsafeWindow.provincenames['p'+pids[i]]);
    span.innerHTML = m + p.join (', ') +'</td></tr></table>';
  },

  aName : '',
  eventSubmit : function (){
    var t = Tabs.AllianceList;
    ById('ptallErr').innerHTML='';
    t.aName = ById('allAllName').value;
    if (t.aName.length < 3){
      ById('ptallErr').innerHTML = 'Entrez au moins 3 caract&egrave;res';
      return;
    }
    var myA = getMyAlliance ();
    ById('altInput').innerHTML = '';
    ById('allListOut').innerHTML = '<BR><BR><CENTER>'+uW.g_js_strings.commonstr.loadingddd+'...</center>';
    if (myA[0]!=0 && myA[1].toLowerCase().indexOf(t.aName.toLowerCase())>=0 )
      t.fetchAllianceList (t.aName, myA[0], t.eventGotAllianceList);
    else
      t.fetchAllianceList (t.aName, null, t.eventGotAllianceList);
  },
  init : function (div){
    var t = Tabs.Search;
    this.cont = div;
    uW.BoPTpd = t.clickedPlayerDetail;
    uW.BoPTpd2 = t.clickedPlayerLeaderboard;
    uW.BoPCpo2 = t.clickedPlayerCheckOnline;
    uW.BoPCplo2 = t.clickedPlayerGetLastLogin;
    var Provinces={1:{name:uW.provincenames["p1"],x:75,y:75},2:{name:uW.provincenames["p2"],x:225,y:75},3:{name:uW.provincenames["p3"],x:375,y:75},4:{name:uW.provincenames["p4"],x:525,y:75},5:{name:uW.provincenames["p5"],x:625,y:75},6:{name:"Paimpont",x:75,y:225},7:{name:"Cam�liard",x:225,y:225},8:{name:"Sarras",x:375,y:225},9:{name:"Canoel",x:525,y:225},10:{name:"Avalon",x:625,y:225},11:{name:"Carmathen",x:75,y:375},12:{name:"Shallot",x:225,y:375},13:{name:"-------",x:375,y:375},14:{name:uW.provincenames["p13"],x:525,y:375},15:{name:uW.provincenames["p14"],x:625,y:375},16:{name:uW.provincenames["p15"],x:75,y:525},17:{name:uW.provincenames["p16"],x:225,y:525},18:{name:uW.provincenames["p17"],x:375,y:525},19:{name:uW.provincenames["p18"],x:525,y:525},20:{name:uW.provincenames["p19"],x:625,y:525},21:{name:uW.provincenames["p20"],x:75,y:675},22:{name:uW.provincenames["p21"],x:225,y:675},23:{name:uW.provincenames["p22"],x:375,y:675},24:{name:uW.provincenames["p23"],x:525,y:675},25:{name:uW.provincenames["p24"],x:625,y:675}}
    if (t.state == null){
      this.cont.innerHTML = '\
        <DIV class=ptentry><table><tr valign=bottom><TD class=xtab width=100 align=right>Type : </td><TD>\
        <SELECT id="srcType">\
          <OPTION value=0>'+uW.g_js_strings.commonstr.barbariancamp+'</option>\
          <OPTION value=1>'+uW.g_js_strings.commonstr.wilderness+'</option>\
	  <OPTION value=2>'+uW.g_js_strings.commonstr.city+'</option>\
	  <OPTION value=3>'+uW.g_js_strings.commonstr.darkForest+'</option>\
        </select></td></tr>\
        </table>\
        <DIV id="srcOpts" style="height:80px"></div></div>\
        <DIV id="srcResults" style="height:400px; max-height:400px;"></div>';
      var psearch = document.getElementById ("pasrcType");
      m = '<TABLE><TR valign=middle><TD class=xtab width=100 align=right>&nbsp; X: </td><TD class=xtab>\
        <INPUT id="srchX" type=text size=3\> &nbsp; Y: <INPUT id="srchY" type=text size=3\>';
      m += '&nbsp;<span><select id="BOprovinceXY"><option>--'+uW.g_js_strings.commonstr.province+'--</option>';
      for (var i in Provinces) {
	    m += '<option value="'+i+'">'+Provinces[i].name+'</option>';
      }
      m += '</select></span> &nbsp; <SPAN id=spInXY></span>';
	  m += '</td></tr><TR><TD class=xtab align=right>Distance : </td><TD class=xtab>entre <INPUT id=srcaDist size=4 value=0 /> et <INPUT id=srcDist size=4 value=10 /></td></tr>';
      m += '<TR><TD class=xtab></td><TD class=xtab><INPUT id=srcStart type=submit value="'+uW.g_js_strings.commonstr.research+'"/></td></tr>';
      m += '</table>';
      document.getElementById ('srcOpts').innerHTML = m;
      var citysrc0=new CdispCityPicker ('srchdcp', document.getElementById ('spInXY'), false, t.clickCitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
      if (Options.srcTypeSelect) 
       document.getElementById ('srcType').value=Options.srcTypeSelect;
      if (Options.srcaDist) 
       document.getElementById ('srcaDist').value=Options.srcaDist;
      if (Options.srcDist) 
       document.getElementById ('srcDist').value=Options.srcDist;    
      document.getElementById ('srcType').addEventListener ('change', function() {
        Options.srcTypeSelect = document.getElementById ('srcType').value;
        saveOptions();
      }, false); 
      document.getElementById ('srcaDist').addEventListener ('change', function() {
              Options.srcaDist = document.getElementById ('srcaDist').value;
              saveOptions();
      }, false); 
      document.getElementById ('srcDist').addEventListener ('change', function() {
              Options.srcDist = document.getElementById ('srcDist').value;
              saveOptions();
      }, false); 
      document.getElementById ('BOprovinceXY').addEventListener ('change', function() {
	  if (this.value >= 1) {
	      document.getElementById ('srchX').value = Provinces[this.value].x;
		document.getElementById ('srchY').value = Provinces[this.value].y;
		  document.getElementById ('srcDist').value = "75";
	  }
	  }, false); 
      document.getElementById ('srcStart').addEventListener ('click', t.clickedSearch, false);
      t.state = 1;
    }
  },
  clickCitySourceSelect : function (city){
    var t = Tabs.Search;
    t.sourceCity = city;
    document.getElementById ('srchX').value=t.sourceCity.x;
    document.getElementById ('srchY').value=t.sourceCity.y;
  },
  opt : {},
  searchRunning : false,
  tilesSearched : 0,
  tilesFound : 0,
  curX : 0,
  curY : 0,
  lastX : 0,
  firstX : 0,
  firstY : 0,
  lastY : 0,
  normalizeCoord : function (x){
    if ( x >= 750)
      x -= 750;
    else if (x < 0)
      x += 750;
    return parseInt (x/5) * 5;
  },
  clickedSearch : function (){
    var t = Tabs.Search;
    if (t.searchRunning){
      t.stopSearch ('RECHERCHE ANNULEE !');
      return;
    }
    t.opt.searchType = document.getElementById ('srcType').value;
    t.opt.startX = parseInt(document.getElementById ('srchX').value);
    t.opt.startY = parseInt(document.getElementById ('srchY').value);
    t.opt.maxDistance = parseInt(document.getElementById ('srcDist').value);
    t.opt.maxDistanceA = parseInt(document.getElementById ('srcaDist').value);
    errMsg = '';
    if (isNaN (t.opt.startX) ||t.opt.startX<0 || t.opt.startX>749)
      errMsg = "X doit &ecirc;tre entre 0 et 749<BR>";
    if (isNaN (t.opt.startY) ||t.opt.startY<0 || t.opt.startY>749)
      errMsg += "Y doit &ecirc;tre entre 0 et 749<BR>";
    if (isNaN (t.opt.maxDistanceA) ||t.opt.maxDistanceA<0)
     errMsg += "La distance mini doit &ecirc;tre sup&eacute;rieur &agrave; 0<BR>";
    if (isNaN (t.opt.maxDistance) ||t.opt.maxDistance<1)
      errMsg += "La distance maxi doit &ecirc;tre sup&eacute;rieur &agrave; 1<BR>";
    if (t.opt.maxDistance<=t.opt.maxDistanceA)
      errMsg += "La distance max doit &ecirc;tre sup&eacute;rieur &agrave; la distance mini<BR>";
    if(t.opt.maxDistanceA > 375)
       errMsg += "La distance max ne peut d&eacute;passer 375 ! au risque de p&ecirc;ter votre navigateur<BR>";
    if (errMsg != ''){
      ById('srcResults').innerHTML = '<FONT COLOR=#660000>ERREUR :</font><BR><BR>'+ errMsg;
      return;
    }

    t.searchRunning = true;
  document.getElementById ('srcStart').value = 'Stopper la recherche';
    m = '<DIV class=boStat><TABLE width=100% cellspacing=0><TR><TD class=xtab width=125><DIV id=statSearched></div></td>\
        <TD class=xtab align=center><SPAN id=statStatus></span></td>\
        <TD class=xtab align=right width=125><DIV id=statFound></div></td></tr></table></div>\
      <TABLE width=100%><TR valign=top><TD><DIV id=divOutTab style="height:'+(Options.HauteurBoite-230)+'px; max-height:'+(Options.HauteurBoite-230)+'px; overflow-y:auto; width:420px;"></div></td>\
      <TD id="tddivOutOpts" width=100% height=100% style="background:#e0e0f0; height:100%; padding:5px"><DIV id=divOutOpts></div></td></tr><tr><td colspan=2><div id=BOdivKOCAttackExport style="position:absolute;background-color:white;height:470px; max-height:470px; overflow-y:auto; width:600px;display:none"></div></td><input type=checkbox id=ShowHideOpts>Voir/Cacher les options (permets d\'avoir le plein &eacute;cran)</tr></table>';
    ById('srcResults').innerHTML = m;
     //
     ById('ShowHideOpts').addEventListener ('click', function (){
		  if (ById("ShowHideOpts").checked) {
		  ById("tddivOutOpts").style.display="none";
		  ById("divOutTab").style.width="710px";
		  } else {
		  ById("tddivOutOpts").style.display="block";
		  ById("divOutTab").style.width="420px";
		  }
	  }, false);
     
    if (t.opt.searchType == 0)
      typeName = 'Camps Barbares';
    else if (t.opt.searchType == 1)
      typeName = 'Terres Sauvages';
    else if (t.opt.searchType == 3)
      typeName = unsafeWindow.g_js_strings.commonstr.darkForest;
	else 
	  typeName = 'Villes';

    m = '<CENTER><B>Recherche de '+ typeName +'<BR>\
        Centre : '+ t.opt.startX +','+ t.opt.startY +'  &nbsp; Distance : '+ t.opt.maxDistanceA +' &agrave; '+ t.opt.maxDistance +'<BR></center>\
        <DIV class=ptentry><TABLE cellspacing=0 width=100%><TR align=center><TD class=xtab colspan=10><B>OPTIONS :</b><BR></td></tr>';
    if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3) {
     m += '<TR><TD class=xtab align=right>Niveau Min. :</td><TD class=xtab> <INPUT id=filMinLvl size=2 value='+ Options.srcMinLevel +' /></td></tr>\
        <TR><TD class=xtab align=right>Niveau Max. :</td><TD class=xtab> <INPUT id=filMaxLvl size=2 value='+ Options.srcMaxLevel +' /></td></tr>';
	}
    if (t.opt.searchType == 1){
      m += '<TR><TD class=xtab align=right>Type TS :</td><TD class=xtab align=right>\
            Woodlands<INPUT id=woodWild type=CHECKBOX'+ (Options.woodWild?' CHECKED':'') +'></td></tr>';
      m += '<TR><TD class=xtab align=right>Prairie/Lac<INPUT  id=foodWild type=CHECKBOX '+ (Options.foodWild?' CHECKED':'') +'></td>\
	       <TD class=xtab align=right>Montagne<INPUT id=mtnWild type=CHECKBOX '+ (Options.mtnWild?' CHECKED':'') +'></td></tr>';
      m += '<TR><TD class=xtab align=right>Plaine<INPUT id=plnWild type=CHECKBOX '+ (Options.plnWild?' CHECKED':'') +'></td>\
           <TD class=xtab align=right>Collines<INPUT id=hillWild type=CHECKBOX'+ (Options.hillWild?' CHECKED':'') +'></td></tr>';
     m += '<TR><TD class=xtab align=right>Filtre :</td><TD class=xtab><SELECT style="width: 135px" id=idTSSrchFilter>\
             <OPTION value=0>Toute les TS</option>\
             <OPTION value=1>Libre seulement</option>\
	     <OPTION value=2>Hostile</option>\
	     <OPTION value=3>Neutre Seulement</option>\
	     <OPTION value=4>Sans alliance Seulement </option>\
             </select></td></tr>';
    } 
    if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3 ) {
        m+= '<TR><TD class=xtab align=right>Trier Par :</td><TD class=xtab><SELECT id=filSortBy>\
          <OPTION value="level" '+ (Options.srcSortBy=='level'?'SELECTED':'')  +'>Niveau</option>\
          <OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>Distance</option>';
          if (t.opt.searchType == 1) {
                m+= '<OPTION value="play" '+ (Options.srcSortBy=='play'?'SELECTED':'')  +'>Joueur</option>';
                m+= '<OPTION value="alli" '+ (Options.srcSortBy=='alli'?'SELECTED':'')  +'>Alliance</option>';
            }    
		  m+= '</select></td></tr>\
			<TR><TD class=xtab align=right>Coords :</td><TD class=xtab><INPUT type=checkbox id=coordsOnly \></td></tr>\
			</table></div><BR><SPAN id=srchSizeWarn></span><DIV id=BOpbSrcExp></div>';
    } else {
			
		m+= '<TR><TD class=xtab align=right >Voir :</td><TD class=xtab align=left ><SELECT style="width: 135px" id=idSrchFilter>\
             <OPTION value=0>Toutes les villes</option>\
             <OPTION value=1>Hostile Seulement</option>\
	     <OPTION value=2>Sous la brume Seulement</option>\
	     <OPTION value=3>Allie Seulement</option>\
	     <OPTION value=4>Amis Seulement</option>\
	     <OPTION value=5>Neutre Seulement</option>\
	     <OPTION value=6>Sans alliance Seulement </option>\
             </select></td></tr>';
	
		m+= '<TR><TD class=xtab align=right>Trier Par :</td><TD class=xtab><SELECT id=filSortBy>\
          <OPTION value="might" '+ (Options.srcSortBy=='might'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.might+'</option>\
          <OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>Distance</option>\
                  <OPTION value="play" '+ (Options.srcSortBy=='play'?'SELECTED':'')  +'>Joueur</option>\
        <OPTION value="alli" '+ (Options.srcSortBy=='alli'?'SELECTED':'')  +'>Alliance</option>\
        </select></td></tr>\
        <tr><TD class=xtab align=right>'+uW.g_js_strings.commonstr.might+' min :</td><TD class=xtab><input size=8 id=filPuissance value="'+Options.filPuissance+'"></td></tr>\
         <tr><TD class=xtab align=right>'+uW.g_js_strings.commonstr.might+' max :</td><TD class=xtab><select id=filPuissanceMax>\
         <option value="500" '+ (Options.filPuissanceMax=='500'?'SELECTED':'')  +'>500</option>\
         <option value="2500" '+ (Options.filPuissanceMax=='2500'?'SELECTED':'')  +'>2 500</option>\
         <option value="10000" '+ (Options.filPuissanceMax=='10000'?'SELECTED':'')  +'>10 000</option>\
         <option value="50000" '+ (Options.filPuissanceMax=='50000'?'SELECTED':'')  +'>50 000</option>\
         <option value="100000" '+ (Options.filPuissanceMax=='100000'?'SELECTED':'')  +'>100 000</option>\
         <option value="500000" '+ (Options.filPuissanceMax=='100000'?'SELECTED':'')  +'>500 000</option>\
         <option value="1000000" '+ (Options.filPuissanceMax=='1000000'?'SELECTED':'')  +'>1 000 000</option>\
         <option value="100000000" '+ (Options.filPuissanceMax=='100000000'?'SELECTED':'')  +'>100 millions</option>\
         <option value="900000000" '+ (Options.filPuissanceMax=='900000000'?'SELECTED':'')  +'>900 millions</option>\</select></td></tr>\
        <TR><TD class=xtab align=right>Coords :</td><TD class=xtab><INPUT type=checkbox id=coordsOnly \></td></tr>\
         </table></div><BR><SPAN id=srchSizeWarn></span><BR><SPAN id=srchSizeWarn></span><DIV id=BOpbSrcExp></div>';	
	}
    ById('divOutOpts').innerHTML = m;
    if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3) {
		ById('filMinLvl').addEventListener ('change', function (){
		  Options.srcMinLevel = ById('filMinLvl').value;
		  saveOptions();
		  t.dispMapTable ();
		  }, false);
		ById('filMaxLvl').addEventListener ('change', function (){
		  Options.srcMaxLevel = ById('filMaxLvl').value;
		  saveOptions();
		  t.dispMapTable ();
		  }, false);
	 }
    ById('filSortBy').addEventListener ('change', function (){
      Options.srcSortBy = ById('filSortBy').value;
      saveOptions();
      t.dispMapTable ();
      }, false);
    ById('coordsOnly').addEventListener ('change', function (){ t.dispMapTable (); }, false);
    if (t.opt.searchType == 1){
    ById('foodWild').addEventListener ('change', function(){
        Options.foodWild = ById('foodWild').checked;
        saveOptions();
        t.dispMapTable ();
        }, false);
    ById('hillWild').addEventListener ('change', function(){
        Options.hillWild = ById('hillWild').checked;
        saveOptions();
        t.dispMapTable();
        }, false);
    ById('mtnWild').addEventListener ('change', function(){
        Options.mtnWild = ById('mtnWild').checked;
        saveOptions();
        t.dispMapTable();
        }, false);
    ById('plnWild').addEventListener ('change', function(){
        Options.plnWild = ById('plnWild').checked;
        saveOptions();
        t.dispMapTable();
        }, false);
    ById('woodWild').addEventListener ('change', function(){
        Options.woodWild = ById('woodWild').checked;
        saveOptions();
        t.dispMapTable ();
        }, false);
   
      ById('idTSSrchFilter').addEventListener ('change', function (){
             Options.TSSrchFilter = (ById('idTSSrchFilter').value);
              saveOptions();
              t.dispMapTable ();
        }, false);
        ById('idTSSrchFilter').value = Options.TSSrchFilter;
    }
    if (t.opt.searchType == 2){

	ById('idSrchFilter').addEventListener ('change', function (){
        Options.citySrchFilter = (ById('idSrchFilter').value);
        saveOptions();
        t.dispMapTable ();
        }, false);

	ById('idSrchFilter').value = Options.citySrchFilter;
	
       
        ById('filPuissance').addEventListener ('change', function (){
        Options.filPuissance = parseInt(ById('filPuissance').value);
        saveOptions();
        t.dispMapTable ();
        }, false);
        ById('filPuissanceMax').addEventListener ('change', function (){
        Options.filPuissanceMax = parseInt(ById('filPuissanceMax').value);
        saveOptions();
        t.dispMapTable ();
        }, false);
	
	}

    t.mapDat = [];
    t.firstX =  t.opt.startX - t.opt.maxDistance;
    t.lastX = t.opt.startX + t.opt.maxDistance;
    t.firstY =  t.opt.startY - t.opt.maxDistance;
    t.lastY = t.opt.startY + t.opt.maxDistance;
    t.tilesSearched = 0;
    t.tilesFound = 0;
    t.curX = t.firstX;
    t.curY = t.firstY;
    var xxx = t.normalizeCoord(t.curX);
    var yyy = t.normalizeCoord(t.curY);
    document.getElementById ('statStatus').innerHTML = 'Recherche sur '+ xxx +','+ yyy;
    setTimeout (function(){Map.request (xxx, yyy, 15, t.mapCallback)}, MAP_DELAY);
  },

  dispMapTable : function (){
    var tileNames = ['Camps barbares', 'Prairie', 'Lac', 'Bois', 'Collines', 'Montagne', 'Plaine', 'Ville', 'Marais', unsafeWindow.g_js_strings.commonstr.darkForest, 'Camelot1',' Camelot2', 'Camelot3',' Camelot4', 'Camelot5','Camelot6','Ruine'];
    var t = Tabs.Search;
    function mySort(a, b){
      if (Options.srcSortBy == 'level'){
        if ((x = a[4] - b[4]) != 0)
          return x;
      }
	  if (Options.srcSortBy == 'might'){
        if ((x = b[10] - a[10]) != 0)
          return x;
      }
      if (Options.srcSortBy == 'alli'){
          
          if (a[11] < b[11]) return -1;
	      else if (a[11] == b[11]) return 0;
	       else return 1;
          
      }
        if (Options.srcSortBy == 'play'){
         
          if (a[9] < b[9]) return -1;
	      else if (a[9] == b[9]) return 0;
	       else return 1;
          
      }
      return a[2] - b[2];
    }

    dat = [];
    for (i=0; i<t.mapDat.length; i++){
      lvl = parseInt (t.mapDat[i][4]);
      type = t.mapDat[i][3];
      puissance = t.mapDat[i][10];
      if (t.opt.searchType == 2 && type == 7 ) {
	  
	  switch(parseInt (Options.citySrchFilter)) {
                case 0:
                 if (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax) {
                  dat.push(t.mapDat[i]);
                 }
                 break;
                case 1:
                   if ((t.mapDat[i][12] == 'hostile') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                    dat.push(t.mapDat[i]);
                   }
                   break;
                case 2:
                   if ((t.mapDat[i][5]===true) && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                    dat.push(t.mapDat[i]);
                   }
                   break;
                case 3:
                   if ((t.mapDat[i][12] == 'allie') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                    dat.push(t.mapDat[i]);
                   }
                   break;
                case 4:
                   if ((t.mapDat[i][12] == 'amicale') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                    dat.push(t.mapDat[i]);
                   }
                   break;
                case 5:
                   if ((t.mapDat[i][12] == 'neutre') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                    dat.push(t.mapDat[i]);
                   }
                   break;
                 case 6:
                   if ((t.mapDat[i][12] == 'unaligned') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                    dat.push(t.mapDat[i]);
                   }
                   break;
             }

		
	  } else {
       if (lvl>=Options.srcMinLevel && lvl<=Options.srcMaxLevel){
        
        if ((t.opt.searchType==3 && (type == 8 || type == 9 || type == 10 || type == 11 || type == 12 || type == 13 || type == 14 || type == 15)) || t.opt.searchType==0
            || (Options.woodWild==1 && type == 3)
            || (Options.hillWild==1 && type ==4)
            || (Options.mtnWild==1 && type==5)
            || (Options.plnWild==1 && type == 6)
            || (Options.foodWild==1 && (type==1 || type==2)))
          if (Options.TSSrchFilter==0)
            dat.push (t.mapDat[i]);
          else if (Options.TSSrchFilter==1 && t.mapDat[i][5]===false)
            dat.push (t.mapDat[i]);
          else if (Options.TSSrchFilter==2 && t.mapDat[i][12] =='hostile')
            dat.push (t.mapDat[i]);  
          else if (Options.TSSrchFilter==3 && t.mapDat[i][12] =='neutre')
            dat.push (t.mapDat[i]);
          else if (Options.TSSrchFilter==4 && t.mapDat[i][12] =='unaligned')
            dat.push (t.mapDat[i]);
        }
       }
    }
    
    ById('statFound').innerHTML = 'Trouv&eacute : '+ dat.length;
    if (dat.length == 0){
      m = '<BR><CENTER>Non trouv&eacute;</center>';
    } else {
      dat.sort(mySort);
      if (ById("coordsOnly").checked)
        m = '<TABLE align=center id=srcOutTab cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>Location</td></tr>';
      else {
        if (t.opt.searchType == 0 || t.opt.searchType == 3) {
			m = '<TABLE id=srcOutTab cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>Lieu</td><TD style="padding-left: 10px">Dist</td><TD style="padding-left: 10px;">Niv</td><TD style="padding-left: 10px;">Type</td></tr>';
		}
		if (t.opt.searchType == 1 ) {
			m = '<TABLE id=srcOutTab cellpadding=2 cellspacing=2><TR style="font-weight: bold"><TD>Lieu</td><TD style="padding-left: 10px">Dist</td><TD style="padding-left: 10px;">Niv</td><TD style="padding-left: 10px;">Type</td><TD style="padding-left: 10px;">Joueur</td><td style="padding-left: 10px;">Puissance</td><td style="padding-left: 10px;">Alliance</td><td>Statut</td><td>Connexion</td></tr>';
		}
		if (t.opt.searchType == 2) {
			 m = '<TABLE id=srcOutTab cellpadding=2 cellspacing=2><TR style="font-weight: bold"><TD>Loc</td><TD >Dist</td><TD>'+unsafeWindow.g_js_strings.commonstr.city+'</td><TD>Proprio</td><TD>Puis.</td><td>Alliance </td><TD width=80% style="font-size:9px;">Plus info</td></tr>';
		}
	
	  }
	  var numRows = dat.length;
      if (numRows > 500 && t.searchRunning){
        numRows = 500;
        ById('srchSizeWarn').innerHTML = '<FONT COLOR=#600000>NOTE : Le tableau montre seulement 500 des '+ dat.length +' resultats jusqu\'a ce que la recherche soit termin&eacute;e.</font>';
      }
      for (i=0; i<numRows; i++){
        m += '<TR valign="top"';
		if (dat[i][12]) m += 'class="'+dat[i][12]+'"';
		
		if (ById("coordsOnly").checked){
		   m += ' ><TD valign="top"><DIV>'+ dat[i][0] +','+ dat[i][1] +'</div></td></tr>';
        } else {
           m += ' ><TD valign="top"><DIV>\
	             <a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ dat[i][0] +','+ dat[i][1] +')</a></div></td>';
   		  if (t.opt.searchType == 2) { 
			m += '<TD align="left"  valign="top"><DIV  onclick="PTscout('+ dat[i][0] +','+ dat[i][1] +');return false;"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/scouting.jpg" title="Eclaireur !">&nbsp;'+ dat[i][2].toFixed(2) +'</a></td><TD align=left>'+ dat[i][8] +'</td><TD valign="top">'+dat[i][9]+'</td><TD valign="top">'+addCommasInt(dat[i][10])+'</td><td>'+dat[i][11]+'</td><td>';
			if (dat[i][5]) {
			 m += '<DIV onclick="BoPTscout('+ dat[i][0] +','+ dat[i][1] +');return false;"><A style="font-size:9px;" >Eclairer</a></div>';
			} else {
			 m += '<DIV onclick="BoPTpd(this, '+ dat[i][7] +')"><A style="font-size:9px;" >Details</a></div> <DIV style="" onclick="BoPTpd2(this, '+ dat[i][7] +')"><A style="font-size:9px;">Tableau Honneur</a></div>\
			 		<DIV style="" onclick="BoPCpo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">Statut</a></div>\
					<DIV style="" onclick="BoPCplo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">Derni&egrave;re Connexion</a></div>';
             m+= '</td></tr>';
            }
		  } else { 
           m += '<TD align=right  valign="top">'+ dat[i][2].toFixed(2) +' &nbsp; </td><TD align=right>'+ dat[i][4] +'</td><TD> &nbsp; '+ tileNames[dat[i][3]];
             +'</td>';
           if (t.opt.searchType == 1) {
            if (dat[i][5]) {
             m += '<td>'+dat[i][9]+'<td>'+addCommasInt(dat[i][10])+'</td><td>'+dat[i][11]+'</td>';
             
             if (dat[i][7] && dat[i][7]!=0) {
             m+='<td><DIV style="" onclick="BoPCpo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">Statut</a></div></td><td><DIV style="" onclick="BoPCplo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">Derni&egrave;re Connexion</a></div></td>';
             } else {
             m+='<td>&nbsp;</td><td>&nbsp;</td>';
             }
             
            
            } else  {
             m +='<td colspan=5 style="text-align=center"><i><b>libre...</b></i>';
            }
		   }else{
            m+="<td></td>";
           }
            m +='</tr>';
		  }
		}
       }
      m += '</table>';
    }
    ById('divOutTab').innerHTML = m;
    dat = null;
  },

  mapDat : [],

  stopSearch : function (msg){
    var t = Tabs.Search;
    document.getElementById ('statStatus').innerHTML = '<FONT color=#ffaaaa>'+ msg +'</font>';
    document.getElementById ('srcStart').value = 'Lancer la recherche';
    ById('srchSizeWarn').innerHTML = '';
    if (t.opt.searchType==0){    
      ById('BOpbSrcExp').innerHTML = '<CENTER>'+ strButton20('Exporter le r&eacute;sultat', 'id=BOpbSrcDoExp') +'</center>'; 
      document.getElementById ('BOpbSrcDoExp').addEventListener ('click', t.exportKOCattack, false);
    }
    if (t.opt.searchType==3){
    	  document.getElementById ('BOpbSrcExp').innerHTML = '<CENTER>'+ strButton20('Attaquer', 'id=BOSrcDoFS') +'</center>';
          document.getElementById ('BOSrcDoFS').addEventListener ('click', t.generateFSList, false);
    }
    if (t.opt.searchType==2){
    	  document.getElementById ('BOpbSrcExp').innerHTML = '<CENTER>'+ strButton20('Liste Eclairage', 'id=pbSrcDoScout') +'</center>';
          document.getElementById ('pbSrcDoScout').addEventListener ('click', t.generateScoutList, false);
	}
    t.searchRunning = false;
  },
  generateFSList :function ()
  {
      var t = Tabs.Search;
      var bulkFS = [];
      for (i=0; i<t.mapDat.length; i++){
         bulkFS.push({x:t.mapDat[i][0], y:t.mapDat[i][1], dist:t.mapDat[i][2], lvl:parseInt(t.mapDat[i][4])});
      }
      bulkFS = bulkFS.sort(function sort(a,b) {a = parseInt(a['dist']);b = parseInt(b['dist']);return a == b ? 0 : (a < b ? -1 : 1);}); 
      if(t.selectedCity == null)
  		t.selectedCity = Cities.cities[0];
      t.ShowFSList (bulkFS, t.selectedCity);
   
  },
 ShowFSList:function (coordlist, city) {
   var t = Tabs.Search;
   t.FScity = city;
   if(t.popFS==null){
	  t.popFS = new CPopup ('BOsrcFS', 0,0, 380,600, true, function (){t.popFS.destroy(); t.popFS=null;});
          t.popFS.centerMe (mainPop.getMainDiv());  
    }
    	var m = '<DIV class=boStat>Options d\'attaque des '+unsafeWindow.g_js_strings.commonstr.darkForest+'</div><div>Niveau : <select id=BOsrcFSLevel><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select>&nbsp<input type=button id=BOsrcFSSave value="Enregistrer"><br>';
    	for (r=1; r<13; r++){
	    m += '<DIV style="float:left;"><img height=20 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg>&nbsp;<input style="border:1px solid black;height:16px;font-size:11px;" id="BOFsUnits'+r+'" type=text size=7 value="0"></DIV>';
      	}
    	m += '</div><br><br><br><br><br><br><DIV>'+unsafeWindow.g_js_strings.commonstr.city+' : <span id=BOsrcFScitypick> </span></div><BR>';
    	m += '<DIV class=boStat>Attaquer depuis <span id=BOsrcFScity>'+city.name+'</span> <BR> Nombre de cibles : '+coordlist.length+'</div>';
    	m += '<DIV style="max-height:220px; overflow-y:auto;"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class=pbTabPadNW><TR style="font-weight:bold; background-color:white"><TD width=15><input type=checkbox id=pbsrcScout_All /></td><TD>Coords</td><td><select id=pbsrcScout_lvl><option value="">Niveau</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td>Dist.</td></tr>';
    	  for(i=0; i<coordlist.length; i++){
    			m += '<TR style="background-color:white"><TD><input type=checkbox name="pbsrcFSCheck" id="pbsrcScoutCheck_'+coordlist[i].x+'_'+coordlist[i].y+'_'+coordlist[i].lvl+'" value="'+coordlist[i].x+'_'+coordlist[i].y+'_'+coordlist[i].lvl+'" /></td><TD>'+coordlist[i].x+ ','+coordlist[i].y+'</td><td>'+coordlist[i].lvl+'</td><td>'+coordlist[i].dist+'</td></tr>';
    	  }
    	m += '</table></div>';
    	m += '<BR><CENTER>'+ strButton20('Commencer l\'attaque', 'id=pbSrcStartScout') +'</center>';
    	m += '<CENTER><DIV style="width:100%; height:100px;max-height:100px; overflow-y:auto;" id=pbSrcScoutResult></DIV></center>';
	

	t.popFS.getMainDiv().innerHTML = m;
	new CdispCityPicker ('BOFSPick', ById('BOsrcFScitypick'), false, function(c,x,y){ById('BOsrcFScity').innerHTML = c.name; t.attackcity = c; }, city.idx);
	
	t.popFS.show(true);
	
	ById('BOsrcFSSave').addEventListener('click', t.enregistrerscrLevel, false);
	ById('BOsrcFSLevel').addEventListener('click', t.changescrLevel, false);
	ById('pbsrcScout_All').addEventListener('change', function(){
			for(k in document.getElementsByName('pbsrcFSCheck'))
				document.getElementsByName('pbsrcFSCheck')[k].checked = ById('pbsrcScout_All').checked;
	}, false);
	ById('pbsrcScout_lvl').addEventListener('change', function(){
			if (ById('pbsrcScout_lvl').value!="") {
				for(k in document.getElementsByName('pbsrcFSCheck')) {
				 var lvl = document.getElementsByName('pbsrcFSCheck')[k].value;
				 if (lvl!==undefined) {
				  var lvll = lvl.split("_");
			          if (lvll[2]==ById('pbsrcScout_lvl').value){
					document.getElementsByName('pbsrcFSCheck')[k].checked = true;
				  }
				 }
			        }
			}
	}, false);
	
	
	
	ById('pbSrcStartScout').addEventListener('click', t.clickedStartFSAttack, false);
	
	t.changescrLevel();
 },
 changescrLevel: function() {
  var t = Tabs.Search;
  if (Options.AttackFSUnits[ById('BOsrcFSLevel').value]!==undefined) {
     for (r=1; r<13; r++){
      ById('BOFsUnits'+r).value=Options.AttackFSUnits[ById('BOsrcFSLevel').value][r];
     } 
   }
 },
 enregistrerscrLevel: function() {
   var t = Tabs.Search;
   Options.AttackFSUnits[ById('BOsrcFSLevel').value]=[];
   for (r=1; r<13; r++){
      Options.AttackFSUnits[ById('BOsrcFSLevel').value][r] = ById('BOFsUnits'+r).value;  
   } 
   saveOptions ();
   t.changescrLevel();
 },
 attacking : false,
 attackcity : null,
 doFSAttack: function(list, city){
  var t = Tabs.Search;
 	ById('pbSrcScoutResult').innerHTML = '';
 	if(list.length < 1){
 		ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>ERREUR : Aucune coordonnee selectionnee</span><br>';
 		t.clickedStartFSAttack();
 		return;
 	}
 	for (var lvl=1;lvl<11; lvl++){ 
         var totalunit=0;
         for (r=1; r<13; r++){
          if (Options.AttackFSUnits[lvl]!=undefined) {
           totalunit += parseInt(Options.AttackFSUnits[lvl][r]);
 	   if(parseInt(Seed.units['city'+city.id]['unt'+r]) < Options.AttackFSUnits[lvl][r]){
 		ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>ERREUR : '+unsafeWindow.unitcost['unt'+r][0]+' non disponible pour le niveau '+lvl+'</span><br>';
 		t.clickedStartFSAttack();
 	 	return;
 	   }
 	  } 
 	 }
 	}
	t.doFSAttackCount(list, city, list.length, 0);
	
 },
 doFSAttackCount : function(list, city, total, count){
	var t = Tabs.Search;
	
        if(!t.attacking){
 		ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>Attaque stoppee</span><BR>';
 		ById('pbSrcStartScout').className = 'button20 ptButton20';
 		ById('pbSrcStartScout').innerHTML = '<SPAN>Commencer l\'attaque</span>';
 		return;
 	}
 	if(total <= (count)){
 		ById('pbSrcScoutResult').innerHTML += 'Termine!<BR>';
 		t.clickedStartFSAttack();
 		return;
 	}
 	var rallypointlevel = t.getRallypoint(city.id);
 	var slots = 0;
        for (z in Seed.queue_atkp['city'+city.id]){           
             slots++;
        }
        if (Seed.queue_atkp['city'+city.id].toSource() == "[]") slots=0;
        if (rallypointlevel==12) rallypointlevel=11;
 	if(slots >= rallypointlevel){
 		setTimeout(function(){t.doFSAttackCount(list, city, total, count)}, 10000);
 		ById('pbSrcScoutResult').innerHTML += 'En attente du point de ralliement...<br>';
 		return;
 	}
 	var coords = list[count].split("_");
 	if(coords[0] == 'undefined' || coords[1] == 'undefined'){
 		ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>ERREUR : Coords invalides</span>';
 		t.clickedStartFSAttack();
 		return;
 	}
 	ById('pbSrcScoutResult').innerHTML += 'Envoi attaque sur '+coords[0]+','+coords[1]+'...';
 	ById('pbsrcScoutCheck_'+coords[0]+'_'+coords[1]+'_'+coords[2]).checked = false;
 	t.sendAttackFS(coords[0], coords[1], coords[2], city, count, function(c){t.doFSAttackCount(list, city, total, c)});
 },
 sendAttackFS : function(x, y, lvl, city, count, notify){
  var t = Tabs.Search;
  count = parseInt(count);
  var totalunit = 0;
  for (r=1; r<13; r++) {
   if (Options.AttackFSUnits[lvl]!=undefined)
       totalunit += parseInt(Options.AttackFSUnits[lvl][r]);
  }        
  if (totalunit>0) {      
  
  
  var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  params.cid = city.id;
  params.kid = 0;
  params.type = 4;
  params.xcoord = x;
  params.ycoord = y;
  for (r=1; r<13; r++)
    params['u'+r]=parseInt(Options.AttackFSUnits[lvl][r]);
  var knt = new Array();
  for (k in Seed.knights['city' + city.id]){
   if (Seed.knights['city' + city.id][k]["knightStatus"] == 1 && Seed.leaders['city' + city.id]["resourcefulnessKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["politicsKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["combatKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["intelligenceKnightId"] != Seed.knights['city' + city.id][k]["knightId"]){
       knt.push ({
                 				Name:   Seed.knights['city' + city.id][k]["knightName"],
                 				Combat:	Seed.knights['city' + city.id][k]["combat"],
                 				ID:	Seed.knights['city' + city.id][k]["knightId"],
       });
    }
  }
  knt = knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);}); 
  if (knt[0]) {
    params.kid= knt[0]["ID"];
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
    		 method: "post",
    		 parameters: params,
    		 loading: true,
    		 onSuccess: function (rslt) {
    		 rslt = eval("(" + rslt.responseText + ")");
    		 if (rslt.ok) {
    			 var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
    			 var ut = unixTime();
    			 var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
    			 var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
    			 for(i = 0; i <= unitsarr.length; i++){
    				if(params["u"+i]){
    				unitsarr[i] = params["u"+i];
    				}
    			 }
    			 var currentcityid = params.cid;
    			 unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
    			 if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
    			 ById('pbSrcScoutResult').innerHTML += 'Envoye !<BR>';
    			 if (notify)
    			  setTimeout(function(){ notify(count+1); }, 1500);
    		 } else {
    			
    			 if (rslt.error_code==104 && rslt.msg=="Ne peux attaquer le marais") {
    			  ById('pbSrcScoutResult').innerHTML += '<span title="'+rslt.msg+'">Impossible - Marais !...</span><BR>';
    			  if (notify) 
    			    setTimeout(function(){ notify(count+1); }, 10000);
    			 } else {
    			   ById('pbSrcScoutResult').innerHTML += '<span title="'+rslt.msg+'">Erreur !...</span><BR>';
    			  if (notify) 
    			   setTimeout(function(){ notify(count); }, 10000);
    			 }
    		  }
    		},
    		onFailure: function () {}
  		}); 
    
    
    
  } else {
   ById('pbSrcScoutResult').innerHTML += 'Erreur chevalier....<BR>';
   if (notify)
    setTimeout(function(){ notify(count); }, 1000);
  }
  
  } else {
  
   ById('pbSrcScoutResult').innerHTML += '<span>Impossible - non parametre !</span><BR>';
   setTimeout(function(){ notify(count+1); }, 500);
  
  }
  
  
 },
 generateScoutList : function (){
     var t = Tabs.Search;
     var bulkScout = [];
     for (i=0; i<t.mapDat.length; i++){

       if (t.mapDat[i][3] == 7){
   
 		if(t.mapDat[i][10] >= Options.filPuissance || t.mapDat[i][5]){
 		if((Options.citySrchFilter=='1' && t.mapDat[i][12] == 'Hostile') ||
 		   (Options.citySrchFilter=='2' && t.mapDat[i][5]===true) ||
 		   (Options.citySrchFilter=='3' && t.mapDat[i][12] == 'Allie') ||
 		   (Options.citySrchFilter=='4' && t.mapDat[i][12]  == 'Amicale') ||
 		   (Options.citySrchFilter=='5' && t.mapDat[i][12] == 'Neutre') ||
 		   (Options.citySrchFilter=='6' && t.mapDat[i][12] == 'unaligned') ||
 		   (Options.citySrchFilter=='0'))
 			bulkScout.push({x:t.mapDat[i][0], y:t.mapDat[i][1], dist:t.mapDat[i][2]});
 		}
 	  }
     }
 	if(t.selectedCity == null)
 		t.selectedCity = Cities.cities[0];
     t.ShowScoutList (bulkScout, t.selectedCity);
   },
   ShowScoutList : function (coordlist, city){
 	var t = Tabs.Search;
 	var popScout = null;
 	t.scoutcity = city;
 	
 	if(popScout==null){
 	  popScout = new CPopup ('pbsrcscout', 0,0, 350,500, true, function (){popScout.destroy(); popScout=null;});
       popScout.centerMe (mainPop.getMainDiv());  
     }
 	var m = '<DIV class=boStat>Options de l\'auto-scout</div>';
 		m += '<DIV>Nombre d\'&eacute;claireur &agrave; envoyer : <input id=pbsrcScoutAmt value="'+Options.srcScoutAmt+'" /></div><BR>';
 		m += '<DIV>Source : <span id=pbsrcScoutcitypick> </span></div><BR>';
 		m += '<DIV class=boStat>Eclairage depuis <span id=pbsrcScoutcity>'+city.name+'</span> <BR> Nombre de cible : '+coordlist.length+'</div>';
 		m += '<DIV style="max-height:220px; overflow-y:auto;"><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabPadNW><TR style="font-weight:bold; background-color:white"><TD width=15><input type=checkbox id=pbsrcScout_All /></td><TD>Target Coords</td></tr>';
 	  for(i=0; i<coordlist.length; i++){
 			m += '<TR style="background-color:white"><TD><input type=checkbox name=pbsrcScoutCheck id="pbsrcScoutCheck_'+coordlist[i].x+'_'+coordlist[i].y+'" value="'+coordlist[i].x+'_'+coordlist[i].y+'" /></td><TD>'+coordlist[i].x+','+coordlist[i].y+'</td></tr>';
 	  }
 	    m += '</table></div>';
 		m += '<BR><CENTER>'+ strButton20('Commencer', 'id=pbSrcStartScout') +'</center>';
 		m += '<CENTER><DIV style="width:70%; max-height:75px; overflow-y:auto;" id=pbSrcScoutResult></DIV></center>';
 	popScout.getMainDiv().innerHTML = m;
 	new CdispCityPicker ('pbScoutPick', ById('pbsrcScoutcitypick'), false, function(c,x,y){ById('pbsrcScoutcity').innerHTML = c.name; t.scoutcity = c; }, city.idx);
 	popScout.getTopDiv().innerHTML = '<CENTER><B>Liste d\'Eclairage</b></center>';
 	popScout.show(true);
 	
 	ById('pbsrcScoutAmt').addEventListener('change', function(){
 		Options.srcScoutAmt = parseInt(ById('pbsrcScoutAmt').value);
 		saveOptions();
 	}, false);
 	ById('pbsrcScout_All').addEventListener('change', function(){
 		for(k in document.getElementsByName('pbsrcScoutCheck'))
 			document.getElementsByName('pbsrcScoutCheck')[k].checked = ById('pbsrcScout_All').checked;
 	}, false);
 	ById('pbSrcStartScout').addEventListener('click', t.clickedStartScout, false);
   },
   scouting : false,
   scoutcity : null,
   doScout : function(list, city){
 	var t = Tabs.Search;
 	ById('pbSrcScoutResult').innerHTML = '';
 	if(list.length < 1){
 		ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>ERREUR : No coords selected</span>';
 		t.clickedStartScout();
 		return;
 	}
 	if(parseInt(Seed.units['city'+city.id]['unt'+3]) < Options.srcScoutAmt){
 		ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>ERREUR : No scouts available</span>';
 		t.clickedStartScout();
 		return;
 	}
 	t.doScoutCount(list, city, list.length, 0);
 	
   },
   	clickedStartScout : function(){
   	var t = Tabs.Search;
   		if(t.scouting == false){
   			t.scouting = true;
   			var ScoutList = [];
   			for(k=0; k<document.getElementsByName('pbsrcScoutCheck').length; k++){
   				if(document.getElementsByName('pbsrcScoutCheck')[k].checked){
   					ScoutList.push(document.getElementsByName('pbsrcScoutCheck')[k].value);
   				}
   			}
   			t.doScout(ScoutList, t.scoutcity);
   			ById('pbSrcStartScout').className = 'button20 pbButCancel';
   			ById('pbSrcStartScout').innerHTML = '<SPAN>Stop</span>';
   		} else {
   			t.scouting = false;
   			ById('pbSrcStartScout').className = 'button20 ptButton20';
   			ById('pbSrcStartScout').innerHTML = '<SPAN>Commencer</span>';
   		}
	},
   doScoutCount : function(list, city, total, count){
 	var t = Tabs.Search;
 	if(!t.scouting){
 		ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>Stopper</span><BR>';
 		ById('pbSrcStartScout').className = 'button20 ptButton20';
 		ById('pbSrcStartScout').innerHTML = '<SPAN>Commencer</span>';
 		return;
 	}
 	if(total <= (count)){
 		ById('pbSrcScoutResult').innerHTML += 'Effectue!<BR>';
 		t.clickedStartScout();
 		return;
 	}
 	var rallypointlevel = t.getRallypoint(city.id);
 	if(rallypointlevel == 12) rallypointlevel = 11;
 	var slots = 0;
        for (z in Seed.queue_atkp['city'+city.id]){
              slots++;
        }
     if  (Seed.queue_atkp['city'+city.id].toSource() == "[]") slots=0;
 
 	if(slots >= rallypointlevel){
 		setTimeout(function(){t.doScoutCount(list, city, total, count)}, 10000);
 		ById('pbSrcScoutResult').innerHTML += 'En attente point de ralliement...<br>';
 		return;
 	}
 	var coords = list[count].split("_");
 	if(coords[0] == 'undefined' || coords[1] == 'undefined'){
 		ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>ERREUR : Coords invalides</span>';
 		t.clickedStartScout();
 		return;
 	}
 	ById('pbSrcScoutResult').innerHTML += 'Eclairage sur '+coords[0]+','+coords[1]+'...';
 	ById('pbsrcScoutCheck_'+coords[0]+'_'+coords[1]).checked = false;
 	t.sendScout(coords[0], coords[1], city, count, function(c){t.doScoutCount(list, city, total, c)});
   },
   sendScout : function(x, y, city, count, notify){
 	var t = Tabs.Search;
 	count = parseInt(count);
 	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
     params.cid = city.id;
 	params.kid = 0;
 	params.type = 3;
 	params.xcoord = x;
 	params.ycoord = y;
 	params.u3 = Options.srcScoutAmt;
 	new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
 		 method: "post",
 		 parameters: params,
 		 loading: true,
 		 onSuccess: function (rslt) {
 		 rslt = eval("(" + rslt.responseText + ")");
 		 if (rslt.ok) {
 			 var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
 			 var ut = unixTime();
 			 var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
 			 var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
 			 for(i = 0; i <= unitsarr.length; i++){
 				if(params["u"+i]){
 				unitsarr[i] = params["u"+i];
 				}
 			 }
 			 var currentcityid = params.cid;
 			 unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
 			 if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
 			 ById('pbSrcScoutResult').innerHTML += 'Envoye!<BR>';
 			 if (notify)
 			  setTimeout(function(){ notify(count+1); }, 1000);
 		 } else {
 			 ById('pbSrcScoutResult').innerHTML += 'Echec! tentative....<BR>';
 			 if (notify)
 			  setTimeout(function(){ notify(count); }, 1000);
 		  }
 		},
 		onFailure: function () {}
   		});
  },
 getRallypoint: function(cityId){
       var t = Tabs.Search;
       cityId = 'city'+cityId;
       for (o in Seed.buildings[cityId]){
 		var buildingType = parseInt(Seed.buildings[cityId][o][0]);
 		var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
 		if (buildingType == 12){
 			return parseInt(buildingLevel);
 			break;
 		}
 	   }
 	  return 0;
    },
 clickedStartFSAttack : function(){
   var t = Tabs.Search;
   	if(t.attacking == false){
   			t.attacking = true;
   			var ScoutList = [];
   			for(k=0; k<document.getElementsByName('pbsrcFSCheck').length; k++){
   				if(document.getElementsByName('pbsrcFSCheck')[k].checked){
   					ScoutList.push(document.getElementsByName('pbsrcFSCheck')[k].value);
   				}
   			}
   			t.doFSAttack(ScoutList, t.attackcity);
   			ById('pbSrcStartScout').className = 'button20 pbButCancel';
   			ById('pbSrcStartScout').innerHTML = '<SPAN>Stopper</span>';
   		} else {
   			t.attacking = false;
   			ById('pbSrcStartScout').className = 'button20 ptButton20';
   			ById('pbSrcStartScout').innerHTML = '<SPAN>Commencer l\'attaque</span>';
		}
 },
 clickedPlayerCheckOnline : function (span, uid){
        var t = Tabs.AllianceList;
      	var s = Tabs.Search;
          span.onclick = '';
          span.innerHTML = uW.g_js_strings.commonstr.loadingddd+"...";
          t.fetchPlayerStatusSimple (uid, function (r) {s.gotPlayerStatus(r, span, uid)});
        },
      
 clickedPlayerGetLastLogin : function (span, uid){
   var t = Tabs.AllianceList;
   var s = Tabs.Search;
          span.onclick = '';
          span.innerHTML = uW.g_js_strings.commonstr.loadingddd+"...";
          t.fetchPlayerLastLogin (uid, function (r) {s.gotPlayerLastLogin(r, span)});
  },
  gotPlayerStatus : function (rslt, span,uid){
      var t = Tabs.AllianceList;
      if (!rslt.ok){
        span.innerHTML = rslt.errorMsg;
        return;
      }
  
      var p = rslt.data;
      if (p[uid] == true) {
        m = '<span style="color:green"><b>En Ligne!</b></span>';
      } else {
         m = '<span style="color:red"><b>Pas en ligne</b></span>';
      }  
      span.innerHTML = m + '';
    },
  
  gotPlayerLastLogin : function (rslt, span){
      var t = Tabs.AllianceList;
      if (!rslt.ok){
        span.innerHTML = rslt.errorMsg;
        return;
      }
  
      var p = rslt.playerInfo;
      var lastLogin = rslt.playerInfo.lastLogin;
      
      if (lastLogin) {
        m = '<span style="color:black">'+lastLogin+'</span>';
      } else {
         m = '<span style="color:red">?</span>';
      }  
      span.innerHTML = m + '';
  },
  exportKOCattack : function (){
     var t = Tabs.Search;
     var bulkAdds = {};
     for (i=1; i<11; i++)
       bulkAdds['lvl'+ i] = [];
     for (i=0; i<t.mapDat.length; i++){
       var lvl = parseInt (t.mapDat[i][4]);
       if (lvl>=Options.srcMinLevel && lvl<=Options.srcMaxLevel && t.mapDat[i][3]==0)
         bulkAdds['lvl'+ lvl].push({x:t.mapDat[i][0], y:t.mapDat[i][1]});
     }
     exportToKOCattackBO.doExport (bulkAdds, t.selectedCity);
  }, 
  mapCallback : function (left, top, width, rslt){
    function insertRow (x, y, msg){
      row = ById('srcOutTab').insertRow(-1);
      row.insertCell(0).innerHTML = x +','+ y;
      row.insertCell(1).innerHTML = distance (t.opt.startX, t.opt.startY, x, y);
      row.insertCell(2).innerHTML = msg;
    }
    var t = Tabs.Search;
    if (!t.searchRunning)
      return;
    if (!rslt.ok){
      t.stopSearch ('ERREUR : '+ rslt.errorMsg);
      return;
    }
    map = rslt.data;
    var userInfo = rslt.userInfo;
    var alliance = rslt.allianceNames;
    for (k in map){
      if (t.opt.searchType==0 && map[k].tileType==51 && !map[k].tileCityId ) {
        type = 0;
      } else if (t.opt.searchType==1 && map[k].tileType>=10 &&  map[k].tileType<=50) {
        if (map[k].tileType == 10)
          type = 1;
        else if (map[k].tileType == 11)
          type = 2;
        else
          type = (map[k].tileType/10) + 1;
      } else if (t.opt.searchType==2 && map[k].tileCityId >= 0 && map[k].tileType > 50 && map[k].cityName) {
		  type = 7;
      } else if (t.opt.searchType==3 && map[k].tileType==54) { 
        type=9;
      } else if (t.opt.searchType==3 && map[k].tileType>100) { 
        type=9 + (map[k].tileType-100);
        
      } else {
        continue;
      }
      dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
      if (dist <= t.opt.maxDistance && dist >= t.opt.maxDistanceA){
		  if (t.opt.searchType==2) {
			var isMisted = map[k].tileUserId == 0 || false;		
			var uu = 'u'+map[k].tileUserId;
			var aU = 'inconnu';
			var aD = 'inconnu';
			var mightU = 0;
			var nameU = 'inconnu';
			if (isMisted) {
				nameU = 'Brume';
				mightU = 0; 
			} else {
				if (userInfo[uu] ) {
					nameU = "<a onclick=getInfoForAnUser('"+ map[k].tileUserId +"');>"+ userInfo[uu].n +"</a>";
					mightU = userInfo[uu].m; 
					aD = getDiplomacy(userInfo[uu].a);
					if ( alliance && alliance['a'+userInfo[uu].a] ) {
						aU = alliance['a'+userInfo[uu].a];
					}
					else {
						aU = '----';
						aD = 'unaligned';
					}
				}
			}
			t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isMisted, map[k].tileCityId, map[k].tileUserId, map[k].cityName,nameU,mightU,aU,aD ]);
		} else {
			isOwned = map[k].tileUserId>0 || map[k].misted;
			var uu = 'u'+map[k].tileUserId;
			var aU = 'inconnu';
			var aD = 'inconnu';
			var nameU = 'inconnu';
			var mightU = 0;
			if (map[k].misted) {
				nameU = 'Sous la Brume';
			}else {
			 if (userInfo[uu] ) {
			   var nameU = "<a onclick=getInfoForAnUser('"+ map[k].tileUserId +"');>"+ userInfo[uu].n +"</a>";
			   mightU = userInfo[uu].m; 
			   aD = getDiplomacy(userInfo[uu].a);
					if ( alliance && alliance['a'+userInfo[uu].a] ) {
						aU = alliance['a'+userInfo[uu].a];
					}
			 }else {
			   var nameU = 'inconnu';
			 }
			}	
			t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isOwned, map[k].tileCityId, map[k].tileUserId, map[k].cityName, nameU, mightU, aU, aD]);       
		}
			++t.tilesFound;
       }   
    }
    t.tilesSearched += (15*15);
    ById('statSearched').innerHTML = 'Trouv&eacute; : '+ t.tilesSearched;
    t.dispMapTable();
    t.curX += 15;
    if (t.curX > t.lastX){
      t.curX = t.firstX;
      t.curY += 15;
      if (t.curY > t.lastY){
        t.stopSearch ('Fini !');
        return;
      }
    }
    var x = t.normalizeCoord(t.curX);
    var y = t.normalizeCoord(t.curY);
    document.getElementById ('statStatus').innerHTML = 'Recherche sur '+ x +','+ y;
    setTimeout (function(){Map.request (x, y, 15, t.mapCallback)}, MAP_DELAY);
  },
};

/*********************************** Players TAB ***********************************/
Tabs.AllianceList = {
  tabOrder: 5,
  tabLabel: uW.g_js_strings.commonstr.player,
  cont : null,
  nombre: null,
  state : null,
  dat : [],

  show : function (){ 
  },

  hide : function (){
  },

  init : function (div){
     var t = Tabs.AllianceList;
        t.cont = div;
        t.nombre=0;
        uW.BoPTgetMembers = t.eventGetMembers;
        uW.PTPaintMembers = t.GetDataForMap;
        uW.BoPTDme = t.eventGetLienMember;
        uW.BoPTpd = t.clickedPlayerDetail;
        uW.BoPTpl = t.clickedPlayerLeaderboard;
        uW.BoPTpl2 = t.clickedPlayerLeaderboard2;
        uW.BoPCplo = t.clickedPlayerGetLastLogin;
        uW.BoPTalClickPrev = t.eventListPrev;
        uW.BoPTalClickNext = t.eventListNext;
   
    if (t.state == null){
      if (getMyAlliance()[0] == 0) {
        t.cont.innerHTML = '<BR><BR><CENTER>'+uW.g_js_strings.membersInfo.youmustbelong+'</center>';
        t.state = 1;
        return;
      }
      var m = '<DIV class=ptentry><TABLE width=100% cellpadding=0>\
          <TR><TD class=xtab align=right></td><TD class=xtab>Nom joueur (Contient) : &nbsp;</td>\
            <TD width=80% class=xtab><INPUT id=allPlayName size=20 type=text/> &nbsp; <INPUT id=playSubmit type=submit value="'+uW.g_js_strings.modal_fow_leaderboard.searchuser+'" /></td>\
            <TD class="xtab ptErrText"><SPAN id=ptplayErr></span></td></tr>\
          <TR><TD class=xtab>&nbsp;</td><TD class=xtab>'+uW.g_js_strings.setDiplomacyWindow.srchalli+' : &nbsp;</td>\
            <TD class=xtab><INPUT id=allAllName type=text /> &nbsp; <INPUT id=allSubmit type=submit value="'+uW.g_js_strings.modal_fow_leaderboard.findalli+'" /></td>\
            <TD class="xtab ptErrText"><SPAN id=ptallErr></span></td></tr>\
            <TR><TD class=xtab>&nbsp;</td><TD class=xtab> &nbsp;\
            <INPUT align=left id=allListSubmit type=submit value="'+uW.g_js_strings.modal_alliance.allilist+'" /></td>\
            <TD class=xtab><INPUT align=right id=allGotoPage type=submit value="Page" />\
             <INPUT align=right id=idPageNum type="text" value='+t.curPage+' size=4 />\
             <INPUT align=left id="idMyAllSubmit" type=submit value="'+ getMyAlliance()[1] +'"/>\
             <INPUT align=left id="idMyTHSubmit" type=submit value="TOP 100"/>\
             <span align=right <b>'+uW.g_js_strings.commonstr.estimatedtime+' : </b></span></td>\
	                  <TD class=xtab ><div><select id="idFindETASelect">\
	             <option value="0" > -- Selectionner -- </option>\
 	<option value="1" >'+unsafeWindow.unitcost["unt1"][0]+'</option>\
        <option value="2" > '+unsafeWindow.unitcost["unt2"][0]+' </option>\
        <option value="3" > '+unsafeWindow.unitcost["unt3"][0]+' </option>\
        <option value="4" > '+unsafeWindow.unitcost["unt4"][0]+' </option>\
        <option value="5" > '+unsafeWindow.unitcost["unt5"][0]+' </option>\
        <option value="6" > '+unsafeWindow.unitcost["unt6"][0]+' </option>\
        <option value="7" > '+unsafeWindow.unitcost["unt7"][0]+' </option>\
        <option value="8" > '+unsafeWindow.unitcost["unt8"][0]+' </option>\
        <option value="9" > '+unsafeWindow.unitcost["unt9"][0]+' </option>\
        <option value="10" > '+unsafeWindow.unitcost["unt10"][0]+' </option>\
        <option value="11" > '+unsafeWindow.unitcost["unt11"][0]+' </option>\
        <option value="12" > '+unsafeWindow.unitcost["unt12"][0]+' </option>\
        </select></div>\
        </td></tr>\
          </table><span style="vertical-align:middle;" id=altInput></span></div>\
          <SPAN id=allListOut></span>';
      t.cont.innerHTML = m;
      
      ById('allSubmit').addEventListener ('click', t.eventSubmit, false);
      ById('playSubmit').addEventListener ('click', t.eventPlayerSubmit, false);
      ById('allAllName').addEventListener ('focus', function (){ById('ptallErr').innerHTML='';}, false);
      ById('idMyTHSubmit').addEventListener ('click', t.eventListTHSubmit, false);
      ById('allPlayName').addEventListener ('focus', function (){ById('ptplayErr').innerHTML='';}, false);
      ById('allListSubmit').addEventListener ('click', t.eventListSubmit, false);
      ById('allGotoPage').addEventListener ('click', t.gotoPage, false);
      ById('idMyAllSubmit').addEventListener ('click', t.showMyAlliance, false);
      ById('allGotoPage').disabled = true;
      ById('idFindETASelect').addEventListener ('click', t.handleEtaSelect, false);
      ById('idFindETASelect').disabled = true;
        
      t.ModelCity=Cities.cities[0];
      t.curPage = 0;
      t.MaxPage = -1;
      t.state = 1;
    }
  },

  pName : '',
  eventPlayerSubmit : function (){
    var t = Tabs.AllianceList;
    ById('ptplayErr').innerHTML='';
    var name = ById('allPlayName').value;
     name = name.replace(/\'/g,"_");
    t.pName = name;
    if (name.length < 3){
      ById('ptplayErr').innerHTML = unsafeWindow.g_js_strings.getAllianceSearchResults.entryatleast3;
      return;
    }
    ById('altInput').innerHTML = '';
     ById('allListOut').innerHTML = '<BR><BR><CENTER>'+unsafeWindow.g_js_strings.commonstr.loadingddd+'</center>';
    t.fetchPlayerList (name, t.eventGotPlayerList);
  },
  eventGetLienMember: function(name) {
    var t = Tabs.AllianceList;
    ById('allPlayName').value = name;
    t.eventPlayerSubmit();   
  }, 
  eventGotPlayerList : function (rslt){
    var t = Tabs.AllianceList;
    if (!rslt.ok){
      ById('allListOut').innerHTML = rslt.errorMsg;
      return;
    }
    t.playerList = rslt.matchedUsers;
        var uList = [];
        for (k in rslt.matchedUsers)
          uList.push (rslt.matchedUsers[k].userId);     
          t.fetchPlayerStatus (uList, function(r) {t.eventGotPlayerOnlineList(r)});    
      },    
        
      eventGotPlayerOnlineList : function (rslt){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
          ById('allListOut').innerHTML = rslt.errorMsg;
          return;
    }
    var m = '<DIV class=boStat>'+uW.g_js_strings.recommendSelectedFriends.playersrch+' : <b>"'+ t.pName +'"</b></div>\
      <DIV style="height:575px; max-height:575px; overflow-y:auto">\
      <TABLE width=95% align=center class=ptTab cellspacing=0><TR style="font-weight:bold"><TD width=20%>'+uW.g_js_strings.commonstr.nametx+'</td>\
      <TD align=right>'+uW.g_js_strings.commonstr.might+' &nbsp;&nbsp;&nbsp;&nbsp;</td><td>KOCMon<TD> &nbsp; En ligne</td><TD width=60%>Informations suppl&eacute;mentaires</td></tr>';
    var row=0;
    var cl='';
    for (k in t.playerList){
      var u = t.playerList[k];
      if (++row % 2)
        cl = 'class=ptOddrow ';
      else
        cl = '';
        if (u.allianceName) { var alliancenammme=u.allianceName; }else {var alliancenammme="---"; }
      m += '<TR '+ cl +'valign=top><TD><A target="_tab" href="http://koc.dunno.com/index.sjs?f=ServersByUser&user_id='+ u.userId +'">'+ u.genderAndName +'</a><br>'+alliancenammme+'<br><A target="_tab" href="http://www.facebook.com/profile.php?id='+ u.fbuid +'">profile</a></td><TD align=center>&nbsp;'+ addCommasInt(u.might) +'&nbsp;</td><td><a target=_blank href="http://kocmon.com/'+unsafeWindow.domainName +'/players/'+ u.userId +'">Info KOCmon</a></td>\
          <TD>'+ (rslt.data[u.userId]?"&nbsp;<SPAN class=boldDarkRed>"+uW.g_js_strings.commonstr.online+"</span>":"") +'</td>\
         <TD><SPAN onclick="BoPTpd(this, '+ u.userId +')"><A>'+uW.g_js_strings.modaltitles.memberdetails+'</a> &nbsp; <BR></span><span onclick="BoPTpl2(this,'+ u.userId+','+rslt.data[u.userId]+')"><A>'+uW.g_js_strings.modaltitles.leaderboard+'</a></span>&nbsp;<br><SPAN onclick="BoPCplo(this, \''+ u.userId +'\')"><A>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+'</a></span></td></tr>';
    }
    m += '</table></div>';
    ById('allListOut').innerHTML = m;
  },
  
  clickedPlayerDetail : function (span, uid){
    var t = Tabs.AllianceList;
    span.onclick = '';
    span.innerHTML = uW.g_js_strings.commonstr.search +': '+ uW.g_js_strings.modaltitles.memberdetails + " ...";
    t.fetchPlayerInfo (uid, function (r) {t.gotPlayerDetail(r, span)});
  },

  clickedPlayerLeaderboard : function (span, uid){
    var t = Tabs.AllianceList;
    span.onclick = '';
    span.innerHTML = uW.g_js_strings.commonstr.search +': '+ uW.g_js_strings.modaltitles.leaderboard + " ...";
    t.fetchLeaderboard (uid, function (r) {t.gotPlayerLeaderboard(r, span)});
  },
  clickedPlayerLeaderboard2 : function (span, uid,status){
      var t = Tabs.AllianceList;
    span.onclick = '';
    span.innerHTML = uW.g_js_strings.commonstr.search +': '+ uW.g_js_strings.modaltitles.leaderboard + " ...";
    t.fetchLeaderboard (uid, function (r) {t.gotPlayerLeaderboard2(r, span,uid,status)});
  },
  
   clickedPlayerGetLastLogin : function (span, uid){
      var t = Tabs.AllianceList;
      span.onclick = '';
      span.innerHTML = uW.g_js_strings.commonstr.search +': '+ uW.g_js_strings.modal_messages_viewreports_view.lastlogin + " ...";
      t.fetchPlayerLastLogin (uid, function (r) {t.gotPlayerLastLogin(r, span)});
    },
   gotPlayerLeaderboard2 : function (rslt,span,uid,status){
      var t = Tabs.AllianceList;
      if (!rslt.ok){
        span.innerHTML = rslt.errorMsg;
        return;
      }
      if (rslt.totalResults == 0){
        span.innerHTML = '<B>'+uW.g_js_strings.commonstr.leaderboard+': </b>'+uW.itemlist.i10021.name+'?<BR>';
        return;
      }
      var myA = getMyAlliance ();
      t.dat = [];
      var p = rslt.results[0];
          if ( myA[0] == p.allianceId)
             t.friendEta = true;
          else
             t.friendEta = false;
          for (var c=0; c<p.cities.length; c++){
                   t.dat.push ([p.displayName, parseInt(p.might), p.officerType, parseInt(p.numCities), parseInt(p.cities[c].tileLevel),
		                parseInt(p.cities[c].xCoord), parseInt(p.cities[c].yCoord), p.cities[c].cityName, 0, c, p.userId, p.avatarId, p.playerSex, p.rank, status, 'NA']);
         
          }
          t.setDistances (Cities.cities[0].x, Cities.cities[0].y);
          t.ModelCity=Cities.cities[0];
          t.setEta();
          t.fetchPlayerLastLogin (uid, function (r) {t.displayPlayer(p.allianceName,r)});
  },
  gotPlayerLeaderboard : function (rslt, span){
    var t = Tabs.AllianceList;
    if (!rslt.ok){
      span.innerHTML = rslt.errorMsg;
      return;
    }
    if (rslt.totalResults == 0){
      span.innerHTML =  '<B>'+uW.g_js_strings.commonstr.leaderboard+': </b>'+uW.itemlist.i10021.name+'?<BR>';
      return;
    }
    var p = rslt.results[0];
    var an = p.allianceName;
    if (!an || an=='' || p.officerType==4)
      an = 'Aucune';
    else
      an += ' ('+ officerId2String(p.officerType) +')';
    m = '<TABLE cellspacing=0 class=ptTab><TR><TD><B>'+uW.g_js_strings.commonstr.leaderboard+' : </b></td><TD colspan=2> '+uW.g_js_strings.commonstr.might+' : '+ p.might  +' &nbsp; '+uW.g_js_strings.commonstr.alliance+' : '+ an +'</td></tr>'; 
    for (var i=0; i<p.cities.length; i++){
      var c = p.cities[i];
      var created = '';
      if (c.dateCreated && c.dateCreated.substr(0,2)=='20')
        created = ' &nbsp; &nbsp; cr&eacute;ation : ' + c.dateCreated.substr(0,10);
      m += '<TR><TD align=right><B>'+uW.g_js_strings.commonstr.city+' #'+ (i+1) +':</b></td><TD> &nbsp; '+ c.cityName 
        + '&nbsp;<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ c.xCoord +',' +c.yCoord+ ')</a>'
        + '</td><TD width=75%> &nbsp; '+uW.g_js_strings.commonstr.level+' : '
        + c.tileLevel +' &nbsp; &nbsp; '+uW.g_js_strings.commonstr.status+': '+ cityStatusString (c.cityStatus) + created +'</td></tr>';
    }  
    span.innerHTML = m + '</table>';
  },
 displayPlayer : function (allName,rslt){
   var t = Tabs.AllianceList;
    function alClickSort (e){
      var t = Tabs.AllianceList;
      var newColNum = e.id.substr(8);
      ById('clickCol'+t.sortColNum).className = 'clickable';
      e.className='clickable clickableSel';
      if (newColNum == t.sortColNum)
        t.sortDir *= -1;
      else
        t.sortColNum = newColNum;
      t.reDisp();
    }
    unsafeWindow.PTalClickSort = alClickSort;
    var m = '<STYLE>.clickable{background-color:#ddd; border:2px outset; border-color:#555; padding-left:5px; padding-right:5px}\
            .clickableSel{background-color:#ffffcc;}\
            .xxtab{background-color:none; padding-left:5px; padding-right:5px;} </style>\
            <DIV class=boStat ><TABLE id=tabAllMembers cellpadding=0  width=100%><TR font-weight:bold"><TD class=xtab>'+uW.g_js_strings.commonstr.alliance+': '+ allName +'</td>\
              <TD class=xtab width=80% align=center>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+' : <SPAN id=lastlogin>'+  rslt.playerInfo.lastLogin+'</span></td><TD class=xtab align=right></td></tr></table></div>\
      <div style="max-height:470px; height:470px; overflow-y:auto;"><TABLE id=tabAllMembers align=center cellpadding=0 cellspacing=0><THEAD style="overflow-y:hidden;">\
      <TR style="font-weight:bold"><TD id=clickCol0 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.player+'</div></a></td>\
        <TD id=clickCol1 onclick="PTalClickSort(this)" class=clickable align=center><A><DIV>'+uW.g_js_strings.commonstr.rank+'</a></div></td>\
        <TD id=clickCol3 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.cities+'</a></div></td>\
        <TD id=clickCol2 onclick="PTalClickSort(this)" class=clickable align=center><A><DIV>'+uW.g_js_strings.commonstr.alliance+'</a></div></td>\
        <TD id=clickCol9 onclick="PTalClickSort(this)" class=clickable align=center><A><DIV>'+uW.g_js_strings.commonstr.online+'</a></div></td>\
        <TD id=clickCol7 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.MapObject.cityname+'</a></div></td>\
        <TD id=clickCol4 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.lvl+'</a></div></td>\
        <TD id=clickCol5 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.coordinates+'</a></div></td>\
        <TD id=clickCol8 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.distance+'</a></div></td>\
        <TD id=clickCol10 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.attack_generateincoming.estimatedarrival+'</a></div></td>\
		<TD class=clickable><A><DIV>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+'</a></div></td></tr></thead>\
      <TBODY id=allBody style="background-color:#ffffff;"></tbody></table></div>\
      <DIV  width:100%; style="top:670px; left:0px; position:absolute; background-color:#ffffff; border-top:1px solid; margin-top:8px; color:#700; font-weight:bold;">';
    ById('allListOut').innerHTML = m; 
    ById('altInput').innerHTML = '<HR><TABLE width=100% cellpaddding=0><TR align=center>\
        <TD class=xtab>'+uW.g_js_strings.commonstr.distance + ' ' + uW.g_js_strings.commonstr.from+' : &nbsp; X: <INPUT size=2 type=text id=plyrX /> Y: <INPUT size=2 type=text id=plyrY /> &nbsp; Ou une ville : <span id=dmcoords></span></td></tr></table>';
    ById('clickCol'+t.sortColNum).className = 'clickable clickableSel';

    t.reDisp();
    new CdispCityPicker ('plyrdcp', document.getElementById ('dmcoords'), true, t.eventCoords, 0).bindToXYboxes(ById('plyrX'), ById('plyrY'));
    ById('idFindETASelect').disabled = false;
  },

  gotPlayerLastLogin : function (rslt, span){
    var t = Tabs.AllianceList;
    if (!rslt.ok){
      span.innerHTML = rslt.errorMsg;
      return;
    }

    var p = rslt.playerInfo;
    var lastLogin = rslt.playerInfo.lastLogin;
    
    if (lastLogin) {
      m = '<span style="color:blue">'+lastLogin+'</span>';
    } else {
       m = '<span style="color:red">-</span>';
    }  
    span.innerHTML = m + '';
  }, 
  gotPlayerDetail : function (rslt, span){
    var t = Tabs.AllianceList;
    if (!rslt.ok){
      span.innerHTML = rslt.errorMsg;
      return;
    }
    var u = rslt.userInfo[0];
    var a = 'Aucune';
    if (u.allianceName)
      a = u.allianceName +' ('+ getDiplomacy(u.allianceId) + ')';
    var m = '<TABLE cellspacing=0 class=ptTab><TR><TD><B>Details :</b> &nbsp; </td><TD>'+uW.g_js_strings.commonstr.alliance+' : '+ a +' &nbsp; '+uW.g_js_strings.commonstr.cities+' : '
          + u.cities +' &nbsp; '+uW.g_js_strings.commonstr.population+' : '+ u.population +'</td></tr><TR><TD></td><TD>'+uW.g_js_strings.commonstr.province+' : ';
    var pids = u.provinceIds.split (',');
    var p = [];
    for (var i=0; i<pids.length; i++)
      p.push(unsafeWindow.provincenames['p'+pids[i]]);
    span.innerHTML = m + p.join (', ') +'</td></tr></table>';
  },

  aName : '',
  eventSubmit : function (){
    var t = Tabs.AllianceList;
    ById('ptallErr').innerHTML='';
    t.aName = ById('allAllName').value;
    if (t.aName.length < 3){
      ById('ptallErr').innerHTML = uW.g_js_strings.getAllianceSearchResults.entryatleast3;
      return;
    }
    var myA = getMyAlliance ();
    ById('altInput').innerHTML = '';
    ById('allListOut').innerHTML = '<BR><BR><CENTER>'+uW.g_js_strings.commonstr.loadingddd+'...</center>';
    if (myA[0]!=0 && myA[1].toLowerCase().indexOf(t.aName.toLowerCase())>=0 )
      t.fetchAllianceList (t.aName, myA[0], t.eventGotAllianceList);
    else
      t.fetchAllianceList (t.aName, null, t.eventGotAllianceList);
  },
  eventListSubmit : function (){
    var t = Tabs.AllianceList;
    var myA = getMyAlliance ();
    ById('allListOut').innerHTML = '<BR><BR><CENTER>'+uW.g_js_strings.commonstr.loadingddd+'...</center>';
    if (myA[0]!=0  ) {
       t.curPage=1;
       t.fetchOtherAllianceInfo ( 1, t.eventGotOtherAlliancePage);
       ById('allGotoPage').disabled = false;
    }
    else {
       ById('allListOut').innerHTML =  uW.g_js_strings.membersInfo.youmustbelong;
    }
  },
  eventListTHSubmit : function (){
      var t = Tabs.AllianceList;
      ById('allListOut').innerHTML = '<BR><BR><CENTER>'+uW.g_js_strings.commonstr.loadingddd+'...</center>';
      t.fetchUserLeaderboard (1, t.eventGetUserLeaderboard);
  },
  eventGotAllianceList : function (rslt){
    var t = Tabs.AllianceList;
    if (!rslt.ok){
      ById('allListOut').innerHTML = rslt.errorMsg;
      return;
    }
    var m = '<DIV class=boStat>'+unsafeWindow.g_js_strings.commonstr.alliances+' <B>"'+ t.aName +'"</b></div>\
    <TABLE><TR style="font-weight:bold"><TD class=xtab>'+unsafeWindow.g_js_strings.commonstr.alliance+'</td><TD class=xtab>'+unsafeWindow.g_js_strings.commonstr.rank+'</td><TD class=xtab>'+unsafeWindow.g_js_strings.commonstr.members+'</td>\
        <TD align=right class=xtab>'+unsafeWindow.g_js_strings.commonstr.might+'</td><TD class=xtab>'+unsafeWindow.g_js_strings.getAllianceSearchResults.currdiplo+'</td><TD class=xtab>'+unsafeWindow.g_js_strings.commonstr.members+'</td><TD class=xtab>'+unsafeWindow.g_js_strings.commonstr.viewmap+'</td></tr>';
    for (k in rslt.alliancesMatched){
      var all = rslt.alliancesMatched[k];
      var dip = '';
      if (all.relation && all.relation==1)
        dip = 'Amicale';
      else if (all.relation && all.relation==2)
        dip = 'Hostile';
      m += '<TR  class="'+ dip + '"><TD class=xtab>'+ all.allianceName +'</td><TD align=right class=xtab>'+ all.ranking +'</td><TD align=right class=xtab>'+ all.membersCount +'</td>\
       <TD align=right class=xtab>'+ addCommasInt(all.might) +'</td><TD class=xtab>'+ dip +'</td>\
       <TD class=xtab><a onclick="BoPTgetMembers('+ all.allianceId +')">'+unsafeWindow.g_js_strings.commonstr.members+'</a></td>\
       <TD class=xtab><a onclick="PTPaintMembers('+ all.allianceId +')">'+unsafeWindow.g_js_strings.commonstr.viewmap+'</a></td></tr>';
    }
    ById('allListOut').innerHTML = m;
  },
  GetDataForMap : function (allianceId) {
    var t = Tabs.AllianceList;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    var Data=[];
    params.perPage = 100;
    params.allianceId = allianceId;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
      	var city = '';
      	for (var i=0; i<rslt.results.length; i++) {
      	    if (rslt.results[i]['userId'] !=0){
	      	    player = rslt.results[i]['cities'];
	      	    for (var ii=0; ii<player.length; ii++) 
	      			Data.push ({X:player[ii]['xCoord'],Y:player[ii]['yCoord']});
	    	}  	
        }
        if (Data != []) t.PaintDataOnMap(Data);
      },
      onFailure: function (rslt) {
        notify ({errorMsg:'AJAX error'});
      },
    });
  },
  PaintDataOnMap : function(Data){
  		var provMapCoordsA = {imgWidth:710, imgHeight:708, mapWidth:670, mapHeight:670, leftMargin:31, topMargin:19};  
  		var map = '<div style="overflow:auto; height:'+(Options.HauteurBoite-140)+'px;max-height:'+(Options.HauteurBoite-140)+'px;"><DIV id=ptAlliProvMap style="height:'+ provMapCoordsA.imgHeight +'px; width:'+ provMapCoordsA.imgWidth +'px; background-repeat:no-repeat; background-image:url(\''+ URL_PROVINCE_MAP +'\')"></div></div>';
		ById('allListOut').innerHTML = map;
		var eMap =  ById('ptAlliProvMap');
		for (var cc=0; cc<Seed.cities.length; cc++) {
		    var city = Seed.cities;
		    var Xplot = parseInt((provMapCoordsA.mapWidth * parseInt(city[cc][2])) / 750);
		    var Yplot = parseInt((provMapCoordsA.mapHeight * parseInt(city[cc][3])) / 750);
		    var cf = document.createElement ('div');
		    cf.style.background = 'black';
		    cf.style.opacity = '1.0';
		    cf.style.position='relative';
		    cf.style.display='block';
		    cf.style.width='14px';
		    cf.style.height='16px';
		    cf.style.border='1px solid #fff';
		    cf.style.color = 'white';
		    cf.style.textAlign = 'center';
		    cf.style.top = (Yplot+provMapCoordsA.topMargin-(cc*16)-8) +'px';      
		    cf.style.left = (Xplot+provMapCoordsA.leftMargin-7) +'px';
		    cf.innerHTML = (cc+1) +'';
		    eMap.appendChild(cf);
		    
		}
		for (var i=0;i<Data.length;i++) {
			var x = parseInt(Data[i]['X']);
			var y = parseInt(Data[i]['Y']);
  	        var xplot = parseInt((provMapCoordsA.mapWidth * x) / 750);
  	        var yplot = parseInt((provMapCoordsA.mapHeight * y) / 750);
  	    	var ce= document.createElement ('div');
  	    		ce.style.background = 'red';
  	    		ce.style.opacity = '1.0';
  	    		ce.style.position='relative';
  	    		ce.style.display='block';
  	    		ce.style.width='4px';
  	    		ce.style.height='4px';
  	    		ce.style.color = 'white';
  	    		ce.style.textAlign = 'center';
  	    	ce.style.top = (yplot+provMapCoordsA.topMargin -(4*i)-((Seed.cities.length)*18)) +'px';      
  	    	ce.style.left = (xplot+provMapCoordsA.leftMargin -2) +'px';
  	    	ce.innerHTML = '<DIV onclick="ptGotoMap('+ x +','+ y +')">&nbsp;</div>';
  	        eMap.appendChild(ce);
  	   }	   
  },  
 showMyAlliance : function (){
    var t = Tabs.AllianceList;
    var myA = getMyAlliance ();
    ById('allListOut').innerHTML = '<BR><BR><CENTER>'+uW.g_js_strings.commonstr.loadingddd+'...</center>';
    if (myA[0]!=0  ) {
       t.eventGetMembers(myA[0]);
    }
    else {
       ById('allListOut').innerHTML =  uW.g_js_strings.membersInfo.youmustbelong;
    }
  },
 curPage : 0,
  MaxPage : 0,

  eventListNext : function (amt){
    var t = Tabs.AllianceList;
    if( parseInt(amt) >= 9999 )
       t.curPage = t.MaxPage;
    else {
	    t.curPage = parseInt(t.curPage) + parseInt(amt);
	    if ( t.curPage > t.MaxPage) {
	      t.curPage = t.MaxPage;
	    }
    }
    ById('allListOut').innerHTML = '<BR><BR><CENTER> ...</center>';
    t.fetchOtherAllianceInfo (t.curPage, t.eventGotOtherAlliancePage);
  },

  eventListPrev : function (amt){
    var t = Tabs.AllianceList;
    if(amt <= -1)
       t.curPage = 1;
    else {
	    t.curPage-=amt;
	    if ( t.curPage < 1 ) {
	      t.curPage = 1;
	    }
    }
    ById('allListOut').innerHTML = '<BR><BR><CENTER> ...</center>';
    t.fetchOtherAllianceInfo (t.curPage, t.eventGotOtherAlliancePage);
  },

  gotoPage : function (){
    var t = Tabs.AllianceList;
    var val = ById('idPageNum').value;
    if (t.MaxPage < 0 ) {
      ById('allListOut').innerHTML = 'List Alliances first.';
      return;
    }
    if (t.MaxPage < 0 || val > t.MaxPage || val < 1) {
      ById('allListOut').innerHTML = 'Page number out of range';
      return;
    }
    t.curPage = val;
    ById('allListOut').innerHTML = '<BR><BR><CENTER> ...</center>';
    t.fetchOtherAllianceInfo (t.curPage, t.eventGotOtherAlliancePage);
  },
  
  eventGetUserLeaderboard: function(rslt) {
   var t = Tabs.AllianceList;
      if (!rslt.ok){
        ById('allListOut').innerHTML = rslt.errorMsg;
        return;
    }
    var m = '<div style="overflow:auto; height:'+(Options.HauteurBoite-145)+'px;max-height:'+(Options.HauteurBoite-145)+'px;"><TABLE width="100%"><thead><TR style="font-weight:bold"> \
          <th class=xtab>'+uW.g_js_strings.commonstr.ranking+'</th><th class=xtab>'+uW.g_js_strings.commonstr.nametx+'</th><th>Avatar</th><th class=xtab>'+uW.g_js_strings.commonstr.might+'</th>\
          <th class=xtab>'+uW.g_js_strings.commonstr.alliance+'</th><th class=xtab>'+uW.g_js_strings.commonstr.rank+'</th><th class=xtab>'+uW.g_js_strings.commonstr.cities+'</th></tr></thead><tbody>';
    ById('allListOut').innerHTML = m;
    for (var i=0; i<rslt.results.length; i++) {
     var resultat = rslt.results[i];
    
     m += '<TR class=xtab><TD class=xtab align=center><b>' + resultat.rank +'</b></td>\
                <td class=xtab><a onclick=BoPTDme("' + resultat.displayName +'");><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/avatars/25/' + resultat.playerSex + '' + resultat.avatarId + '.jpg"></a></td>\
     		<TD class=xtab>' + resultat.displayName +'</td>\
     		<td class=xtab>' + resultat.might + '</td>\
     		<td class=xtab><a onclick="BoPTgetMembers('+ resultat.allianceId +')">' + resultat.allianceName + '</a></td>\
     		<td class=xtab>' + officerId2String(resultat.officerType) + '</td><td class=xtab>' + resultat.numCities + '</td>\
     		</tr>';
     m += '</div>';
     ById('allListOut').innerHTML = m;
    }
  },
  fetchUserLeaderboard: function(pagNum, notify) {
        var t = Tabs.AllianceList;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.page = pagNum;
        params.perPage = 100;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
          method: "post",
          parameters: params,
          onSuccess: function (rslt) {
            notify (rslt);
          },
          onFailure: function (rslt) {
            notify (rslt);
          },
      });
  },
  
  
  eventGotOtherAlliancePage : function (rslt){
    var t = Tabs.AllianceList;
    if (!rslt.ok){
      ById('allListOut').innerHTML = rslt.errorMsg;
      return;
    }

    ById('idPageNum').value = t.curPage;

    t.MaxPage=rslt.noOfPages;

    var m = '<div style="overflow:auto; height:'+(Options.HauteurBoite-230)+'px;width:95%;"><TABLE><thead><TR style="font-weight:bold"> \
   <th class=xtab>'+uW.g_js_strings.commonstr.rank+'</th><th class=xtab>'+uW.g_js_strings.modaltitles.alliance+'</th><th class=xtab>'+uW.g_js_strings.commonstr.chancellor+'</th><th class=xtab>'+uW.g_js_strings.commonstr.members+'</th>\
        <th align=right class=xtab>'+uW.g_js_strings.commonstr.might+'</th><th align=right class=xtab>'+uW.g_js_strings.commonstr.glory+'</th><th class=xtab>'+uW.g_js_strings.getAllianceSearchResults.currdiplo.substr(0,10)+'</th><th class=xtab>'+unsafeWindow.g_js_strings.commonstr.members+'</th><th class=xtab>'+unsafeWindow.g_js_strings.commonstr.viewmap+'</th></tr></thead><tbody>';
    ById('allListOut').innerHTML = m;

    for (var i=0; i<rslt.otherAlliances.length; i++) {
      var alliance = rslt.otherAlliances[i];
      var dip = '';
      dip = getDiplomacy(alliance.allianceId);

      m += '<TR class="'+ dip + '"><TD align=right class=xtab>'+ alliance.ranking +'</td><TD class=xtab>' + alliance.name +'</td><TD class=xtab>' + alliance.hostGenderAndName +'</td><TD align=right class=xtab>'+ alliance.membersCount +'</td>\
       <TD align=right class=xtab>'+ addCommasInt(alliance.might) +'</td><TD align=right class=xtab>'+ addCommasInt(alliance.glory) +'</td><TD class=xtab>'+ dip +'</td>\
       <TD class=xtab><a onclick="BoPTgetMembers('+ alliance.allianceId +')">'+uW.g_js_strings.commonstr.members+'</a></td>\
       <TD class=xtab><a onclick="PTPaintMembers('+ alliance.allianceId +')">'+uW.g_js_strings.commonstr.viewmap+'</a></td></tr>';
    }
    m += '</tbody></TABLE><div style="font-weight:bold; height:20px;width:95%;text-align:center;"><span><center><a onclick="BoPTalClickPrev(-1)"> ['+uW.g_js_strings.commonstr.first+'] </a><a onclick="BoPTalClickPrev(10)"> [-10] </a><a onclick="BoPTalClickPrev(5)"> [-5] </a><a onclick="BoPTalClickPrev(1)"> ['+uW.g_js_strings.commonstr.previous+'] </a> \
          <a onclick="BoPTalClickNext(1)"> ['+uW.g_js_strings.commonstr.next+'] </a><a onclick="BoPTalClickNext(5)"> [+5] </a><a onclick="BoPTalClickNext(10)"> [+10] </a><a onclick="BoPTalClickNext(9999)"> [End] </a> </span></div>';
    m += '</div>';
    ById('allListOut').innerHTML = m;
 },

  showCurrentPage : function (){
    var t = Tabs.AllianceList;
    var myA = getMyAlliance ();

    ById('allListOut').innerHTML = '<BR><BR><CENTER>'+uW.g_js_strings.commonstr.loadingddd+'...</center>';
    if (myA[0]!=0  ) {
       t.fetchOtherAllianceInfo ( t.curPage, t.eventGotOtherAlliancePage);
    }
    else {
       t.fetchOtherAllianceInfo ( t.curPage, t.eventGotOtherAlliancePage);
    }

  },

  
  eventGotMemberList : function (rslt){
     var t = Tabs.AllianceList;
     if (!rslt.ok){
       ById('allListOut').innerHTML = rslt.errorMsg;
       return;
     }
     t.memberListRslt = rslt;
     var uList = [];
     for (k in rslt.results)
       uList.push (rslt.results[k].userId);     
     t.fetchPlayerStatus (uList, function(r){t.eventGotMemberOnlineList(r)});    
   },    
     
  eventGotMemberOnlineList : function (rslt){
    var t = Tabs.AllianceList;
    var numInvalid = 0;
    var numPlayers = 0;
    var myA = getMyAlliance ();
    t.dat = [];
    for (var i=0; i<t.memberListRslt.results.length; i++){
      p = t.memberListRslt.results[i];
      if (p.userId == 0){
        ++numInvalid;
      } else {
        ++numPlayers;
        if ( myA[0] == p.allianceId)
          t.friendEta = true;
	        else
           t.friendEta = false;
        for (var c=0; c<p.cities.length; c++){
           t.dat.push ([p.displayName, parseInt(p.might), p.officerType, parseInt(p.numCities), parseInt(p.cities[c].tileLevel),
               parseInt(p.cities[c].xCoord), parseInt(p.cities[c].yCoord), p.cities[c].cityName, 0, c, p.userId, p.avatarId, p.playerSex, p.rank, rslt.data[p.userId]?1:0, 'NA']);
        }
      }
    }
    t.setDistances (Cities.cities[0].x, Cities.cities[0].y);
    t.ModelCity=Cities.cities[0];
    t.setEta();
    t.displayMembers (t.memberListRslt.allianceName, numPlayers);
  },
  reDisp : function (){
    var t = Tabs.AllianceList;   
    function sortFunc (a, b){
          var t = Tabs.AllianceList;
     if (typeof(a[t.sortColNum]) == 'number'){
             if (t.sortDir > 0)
               return a[t.sortColNum] - b[t.sortColNum];
             else
               return b[t.sortColNum] - a[t.sortColNum];
           } else if (typeof(a[t.sortColNum]) == 'boolean'){
         
     	return 0;        
           } else {
             if (t.sortDir > 0)
               return a[t.sortColNum].localeCompare(b[t.sortColNum]);
             else
               return b[t.sortColNum].localeCompare(a[t.sortColNum]);
      }
    }
    t.dat.sort (sortFunc);
    var m = '';
    var tbody = ById('allBody');
    tbody.innerHTML ='';
    tbody.style.maxHeight = '';
    var csvXL="";
    for (var i=0; i<t.dat.length; i++){ 
    	if (i % 2 == 0) {
        		 tabclass = 'xxtab';
        	} else {
        		tabclass = 'xxtab_even';
    	} 
        m += '<TR><TD  class='+ tabclass +' align=left><a onclick=BoPTDme("' +  t.dat[i][0] +'");><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/avatars/25/'+t.dat[i][12]+''+t.dat[i][11]+'.jpg" align=absmiddle></a>&nbsp;<a onclick=getInfoForAnUser("'+ t.dat[i][10] +'");>'+ t.dat[i][0] +'</a></td><TD align=right class='+ tabclass +'>'+ addCommasInt(t.dat[i][1]) +'</td><TD align=center class='+ tabclass +'>'+ t.dat[i][3] +'</td>\
	                <TD class='+ tabclass +' align=left><span title="Classement : '+t.dat[i][13]+' joueur">'+ officerId2String(t.dat[i][2])  +'</span></td><TD class='+ tabclass +' align=left>'+ (t.dat[i][14]?'<SPAN class=boldDarkRed>LIGNE</span>':'') +'</td><TD class='+ tabclass +' align=left><span title="'+ t.dat[i][7]+'">'+ t.dat[i][7].substring(0,8) +'</span></td><TD align=right class='+ tabclass +'>'+ t.dat[i][4] +'</td>\
	                <TD align=left class='+ tabclass +'>\
	                <a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ t.dat[i][5] +','+ t.dat[i][6] +')</a>\
	                </td><TD align=left class=xxtab style="padding-right:20px;">'+ t.dat[i][8].toFixed(2) +'</td>';
      	m += '<TD nowrap class=xxtab align=left>'+ (t.dat[i][15]?'<SPAN>'+ (t.dat[i][15]>0?timestr(t.dat[i][15],1):'NA') +'</span>':'<SPAN>NA</span>') +'</td><td class='+ tabclass +' align=left><SPAN onclick="BoPCplo(this, \''+ t.dat[i][10] +'\');"><A>?</a></span><td></tr>';
	csvXL += t.dat[i][0]+';'+t.dat[i][1]+';'+t.dat[i][5]+';'+t.dat[i][6]+';'+t.dat[i][4]+';'+t.dat[i][8]+';'+t.dat[i][7]+'\n';
    }
    m += '<tr><td colspan=11><textarea cols="55" rows="12" onclick="this.focus();this.select();" id="cutAndPaste" name="csv">Joueur;'+uW.g_js_strings.commonstr.might+';X;Y;Niveau;Distance;Ville\n'+csvXL+'</textarea><br><b>Export XLS (pour toi public:</b><bR>Copiez le contenu de la zone, coller ensuite le contenu dans blocnote et enregistrer le fichier en .cvs</tr>';
   
   var tbody = ById('allBody');
    tbody.style.maxHeight = '';
    tbody.innerHTML = m;
    ById("cutAndPaste").innerHTML=csvXL;
    if (parseInt(tbody.clientHeight) > 475){
      tbody.style.height = '475px';
      tbody.style.maxHeight = '475px';
    }
  },
  setDistances : function (x, y){
    var t = Tabs.AllianceList;
    for (var i=0; i<t.dat.length; i++)
      t.dat[i][8] = distance (x, y, t.dat[i][5], t.dat[i][6]);
  },
  friendEta:false,
  setEta : function (){
    var t = Tabs.AllianceList;
    for (var i=0; i<t.dat.length; i++) {
      if (t.dat[i][8]) {
        if (ById('idFindETASelect').value>0) {
         var eta = estETA(parseFloat(t.dat[i][8]), ById('idFindETASelect').value, t.ModelCity.id,4);
         if (t.friendEta)
           t.dat[i][15] = eta.friendETA;
         else
           t.dat[i][15] = eta.ETA;
        }
      }
    }
  },
  handleEtaSelect : function (){
    var t = Tabs.AllianceList;
    t.setEta();
    t.reDisp();
  },
  sortColNum : 1,
  sortDir : 1,
  displayMembers : function (allName, numPlayers){
    var t = Tabs.AllianceList;
    function alClickSort (e){
      var t = Tabs.AllianceList;
      var newColNum = e.id.substr(8);
      ById('clickCol'+t.sortColNum).className = 'clickable';
      e.className='clickable clickableSel';
      if (newColNum == t.sortColNum)
        t.sortDir *= -1;
      else
        t.sortColNum = newColNum;
      t.reDisp();
    }
    unsafeWindow.PTalClickSort = alClickSort;
    var m = '<STYLE>.clickable{background-color:#ddd; border:2px outset; border-color:#555; padding-left:5px; padding-right:5px}\
            .clickableSel{background-color:#ffffcc;}\
            .xxtab{background-color:none; padding-left:5px; padding-right:5px;} </style>\
      <DIV class=boStat><TABLE id=tabAllMembers cellpadding=0  width=100%><TR font-weight:bold"><TD class=xtab> &nbsp; '+ allName +'</td>\
        <TD class=xtab width=80% align=center>'+uW.g_js_strings.commonstr.distance + ' ' + uW.g_js_strings.commonstr.from+' <SPAN id=distFrom>'+ Cities.cities[0].name +' ('+ Cities.cities[0].x +','+ Cities.cities[0].y +')</span></td><TD class=xtab align=right>'+ numPlayers +' joueurs trouv&eacute;s &nbsp; </td></tr></table></div>';
     m += '<div style="top:200px;left:5px;width:98%; position:absolute;max-height:'+(Options.HauteurBoite-220)+'px;height:'+(Options.HauteurBoite-220)+'px;overflow:auto;">\
      <TABLE id=tabAllMembers align=center cellpadding=0 cellspacing=0><THEAD>\
      <TR style="font-weight:bold"><TD id=clickCol0 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.player+'</div></a></td>\
        <TD id=clickCol1 onclick="PTalClickSort(this)" class=clickable align=center><A><DIV>'+uW.g_js_strings.commonstr.might+'</a></div></td>\
        <TD id=clickCol3 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.cities+'</a></div></td>\
        <TD id=clickCol2 onclick="PTalClickSort(this)" class=clickable align=center><A><DIV>'+uW.g_js_strings.commonstr.rank+'</a></div></td>\
        <TD id=clickCol14 onclick="PTalClickSort(this)" class=clickable align=center><A><DIV>'+uW.g_js_strings.commonstr.online+'</a></div></td>\
        <TD id=clickCol7 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.MapObject.cityname+'</a></div></td>\
        <TD id=clickCol4 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.lvl+'</a></div></td>\
        <TD id=clickCol5 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.coordinates+'</a></div></td>\
        <TD id=clickCol8 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.commonstr.distance+'</a></div></td>\
        <TD id=clickCol15 onclick="PTalClickSort(this)" class=clickable><A><DIV>'+uW.g_js_strings.attack_generateincoming.estimatedarrival+'</a></div></td>\
        <TD class=clickable><A><DIV>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+'</div></a></td></tr></thead>\
      <tbody id=allBody ></tbody></table></div>\
      <DIV style="top:'+(Options.HauteurBoite-30)+'px; left:0px; position:absolute; width:100%; border-top:1px solid; margin-top:8px; color:#700; font-weight:bold;"></div>';        
    ById('allListOut').innerHTML = m;
    ById('altInput').innerHTML = '<HR><TABLE width=100% cellpaddding=0><TR align=center>\
        <TD class=xtab>'+uW.g_js_strings.commonstr.distance + ' ' + uW.g_js_strings.commonstr.from+' : &nbsp; X: <INPUT size=2 type=text id="plyrX" /> Y: <INPUT size=2 type=text id="plyrY" /> &nbsp; Ou, choisissez une ville : <span id=dmcoords></span></td></tr></table>';
    ById('clickCol'+t.sortColNum).className = 'clickable clickableSel';
    t.reDisp();
    new CdispCityPicker ('plyrdcp', document.getElementById ('dmcoords'), true, t.eventCoords, 0).bindToXYboxes(ById('plyrX'), ById('plyrY'));
    ById('idFindETASelect').disabled = false;
    
 },
    
 eventCoords : function (city, x, y){
    var t = Tabs.AllianceList;
    var m = '';
    if (city != null)
      m = city.name +' ('+ city.x +','+ city.y +')';
    else
      m = x +','+ y;
    var distFrom = ById('distFrom');
    if (distFrom)
        distFrom.innerHTML = m;
    t.ModelCity=city;
    t.setDistances(x,y);
    t.setEta(x,y);
    t.reDisp();
  },
  
  eventGetMembers : function (aid){
    var t = Tabs.AllianceList;
    ById('allListOut').innerHTML = '<BR><BR><CENTER>'+uW.g_js_strings.commonstr.loadingddd+'...</center>';
    t.fetchAllianceMemberList (aid, null, t.eventGotMemberList);
  },

  fetchAllianceMemberList : function (allianceId, allianceName, notify) {
    var t = Tabs.AllianceList;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.perPage = 100;
    if (allianceName)
      params.allianceName = allianceName;
    if (allianceId && allianceId != 0)
      params.allianceId = allianceId;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify (rslt);
      },
    });
  },

 
  fetchLeaderboard : function (uid, notify) {
    var t = Tabs.AllianceList;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.userId = uid;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify (rslt);
      },
    });
  },
  fetchAllianceList : function (allianceName, myAid, notify) {
    var t = Tabs.AllianceList;
    function combineResults (rsltA, rsltM, notify){
      if (!rsltA.ok){
        if (rsltA.msg.indexOf("No alliance found under")!=0 || !rsltM.ok){
          notify (rsltA);
          return;
        }
        rsltA.ok = true;
        rsltA.count = 0;
        rsltA.alliancesMatched = {};
      }
      if (rsltM.ok){
        rsltA.alliancesMatched['a'+rsltM.allianceInfo.allianceId] = {allianceId: rsltM.allianceInfo.allianceId, allianceName: rsltM.allianceInfo.allianceName,
              membersCount: rsltM.allianceInfo.members, relation: null, might: rsltM.allianceInfo.might, ranking: rsltM.allianceInfo.ranking};
        ++rsltA.count;
      }
      notify (rsltA);
    }
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.allianceName = allianceName;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetSearchResults.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (myAid!=null && myAid>0)
          t.fetchMyAllianceInfo  (function (r){ combineResults (rslt, r, notify)});
        else
          notify (rslt);
      },
      onFailure: function (rslt) {
        notify (rslt);
      },
    });
  },
  fetchOtherAllianceInfo : function (pageNum, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.pageNo = pageNum;
    params.cityId = unsafeWindow.currentcityid;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetOtherInfo.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onSuccess: function (rslt) {
        notify (rslt);
      },
    });
  },

  fetchMyAllianceInfo : function (notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetInfo.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onSuccess: function (rslt) {
        notify (rslt);
      },
    });
  },

  fetchPlayerList : function (name, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.searchName = name;
    params.subType = "ALLIANCE_INVITE";
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/searchPlayers.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onSuccess: function (rslt) {
        notify (rslt);
      },
    });
  },

  fetchPlayerInfo : function (uid, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.uid = uid;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserGeneralInfo.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onSuccess: function (rslt) {
        notify (rslt);
      },
    });
  },

  
    fetchPlayerLastLogin : function (uid, notify){
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.pid = uid;
      new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (rslt) {
          notify (rslt);
        },
        onSuccess: function (rslt) {
          notify (rslt);
        },
      });
  },
  fetchPlayerStatusSimple : function (uid, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.checkArr = uid;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
          method: "post",
          parameters: params,
          onSuccess: function (rslt) {
            notify (rslt);
          },
          onSuccess: function (rslt) {
            notify (rslt);
          },
        });
    },
  
  fetchPlayerStatus : function (uidArray, notify){
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.checkArr = uidArray.join(',');
      new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (rslt) {
          notify (rslt);
        },
        onFailure: function (rslt) {
          notify ({errorMsg:'AJAX error'});
        },
      });
  },
 
  ModelCity : {},

};


/*************** TRANSPORT **********/
Tabs.TranspAuto = {
 tabOrder: 6,
 tabLabel: 'Transport',
 cont : null,
 displayTimer : null,
 state : null,
 curTabBut : null,
 curTabName : null,
 sourceCity : {},
 destinationCity : {},
 rows : [],
  timer: null,
  traderState: [],
  reapproState: [],
  lTR: [],
  tradeRoutes: [],
  checkdotradetimeout: null,
  count:0,
  check:false,
 show : function (){
   var t = Tabs.TranspAuto;
   if (document.getElementById ('maparea_map').style.display!="none") {
     if (t.destinationCityx) {
                      t.destinationCityx.value = document.getElementById ('mapXCoor').value;
                      t.destinationCityy.value = document.getElementById ('mapYCoor').value;
                     }
   }
   if (t.curTabBut) {
    var but=t.curTabBut;
    t.show2();
   }
 },
 hide : function (){
    var t = Tabs.TranspAuto;
    clearTimeout (t.displayTimer);
    clearTimeout (t.timer);
  },
  
  init : function (div){  
   var t = Tabs.TranspAuto;
   unsafeWindow.BOestimeres = t.estimerRes;
   t.traderState = {running: false,};
   t.reapproState = {running: false,city:-1,unit:9,mini:1000};
   t.readTraderState();
   t.readReapproState();
   
   t.readTradeRoutes();  
   t.e_tradeRoutes();
	    
 
   AddSubTabLink('Transport', t.toggleTraderState, 'pbtrantab');
   AddSubTabLink('Appro', t.toggleReapproState, 'boreapprotab');
   if (t.reapproState.running == false) {
       	       updatebotbutton('Appro - OFF', 'boreapprotab');
             } else {
       	      updatebotbutton('Appro - ON', 'boreapprotab');
       	      setTimeout(t.actionreappro,10000);
   }
   if (t.traderState.running == false) {
       	       updatebotbutton('Transp - OFF', 'pbtrantab');
             } else {
       	       updatebotbutton('Transp - ON', 'pbtrantab');
    }
    window.addEventListener('unload', t.onUnload, false);
    t.cont = div;
    t.cont.innerHTML = '<TABLE class=ptTab align=center><TR><TD><INPUT class=bopbSubtab ID=BoTrpSubM type=submit value="Manuel"></td>\
             <TD><INPUT class=bopbSubtab ID=BoTrpSubA type=submit  value="Automatique"></td><TD><INPUT class=bopbSubtab ID=BoTrpSubR type=submit  value="Approvisionner"></td></tr></table>\
         <DIV id="BoTrpOutput" style="margin-top:5px; background-color:white; height:'+(Options.HauteurBoite-65)+'px;max-height:'+(Options.HauteurBoite-65)+'px;overflow-y:auto"></div>';
        t.TransportDiv = ById('BoTrpOutput'); 
  ById('BoTrpSubA').addEventListener('click', e_butSubtab, false);
  ById('BoTrpSubM').addEventListener('click', e_butSubtab, false);
  ById('BoTrpSubR').addEventListener('click', e_butSubtab, false);
  
  
  
  
     changeSubtab (ById('BoTrpSubM'));  

      function e_butSubtab (evt){
          changeSubtab (evt.target);   
      }
    
      function changeSubtab (but){
          if (but == t.curTabBut)
            return;
          if (t.curTabBut){
            t.curTabBut.className='bopbSubtab'; 
            t.curTabBut.disabled=false;
          }
          t.curTabBut = but;
          but.className='bopbSubtab bopbSubtabSel'; 
          but.disabled=true;
          t.curTabName = but.id.substr(8);
          t.show2();
      }  
      var final = 0;
      if (t.reapproState.city>=0) {
      for(var i=0; i<Cities.numCities; i++) {
          var x2 = parseInt(Cities.cities[i].x);
          var x1 = parseInt(Cities.cities[t.reapproState.city].x);
          var y2 = parseInt(Cities.cities[i].y);
          var y1 = parseInt(Cities.cities[t.reapproState.city].y);
          var dist = distance (x1, y1, x2, y2);
          var m = estETA(dist,t.reapproState.unit,Cities.cities[t.reapproState.city].id,1);  
           if (m.friendETA>final)
            final=m.friendETA;
        }
        Options.reapprointerval = parseInt(final/60*2+10);
       }    
  },
   show2 : function (){
     var t = Tabs.TranspAuto
     t.state = null;
     clearTimeout (t.displayTimer);
     clearTimeout (t.timer);
     if (t.curTabName == 'M')
       t.showManuel();
     else  if (t.curTabName == 'R')
       t.showReappro();
     else {
       t.showAuto();
       t.showTimer();	
     }
  },
  showTimer: function() {
   var t = Tabs.TranspAuto;
   t.updateTroops();
   t.updateResources();  
   t.timer = setTimeout (t.showTimer, 1000); 
  },
  showReappro: function () {
   var t = Tabs.TranspAuto;
   var m = '<DIV id=pbTowrtDivF class=boStat>APPROVISIONNER AUTOMATIQUE - CONFIGURATION - <input type=button value="?" id=boaideappro class=boAide></div><TABLE id=pbtraderfunctions width=100% height=0% class=pbTab><TR align="center">';
   if (t.reapproState.running == false) {
               m += '<TD><INPUT id=boReapproState type=submit value="Appro = OFF"></td>';
     	       updatebotbutton('Appro - OFF', 'boreapprotab');
           } else {
               m += '<TD><INPUT id=boReapproState type=submit value="Appro = ON"></td>';
     	      updatebotbutton('Appro - ON', 'boreapprotab');
   }
   m += '<td><input type=button value="Valeurs AUTOMATIQUE" id=BORecupReappro></td><td><input type=button value="Enregistrer" id="boReappro"><td><span title="Ce temps se recalcule TOUT seul a chaque ouverture de la boite ! il est defini par le temps le plus eleve entre le QG et les villes secondaires + 10 minutes.">Interval automatique : <INPUT id=pbreapprointerval type=text size=2 READONLY value="'+Options.reapprointerval+'"\> minutes</td></tr></table>';
   m += '<DIV id=pbReapproDivDRoute class=boStat>CONFIGURER VOS VILLES</div>';
   m += '<TABLE id=pbaddReapproroute width=95% height=0% class=pbTab><TR align="left">';
   m += '<TR align="left"><TD colspan=2>Ville de provision :</td> <TD colspan=3><DIV style="margin-bottom:10px;"><span id=borescity></span></div></td><td colspan=4>'+uW.g_js_strings.commonstr.troops+' : <select id="BOApproUnit"><option value=9>Wagons</option><option value=7>Cavalerie legere</option><option value=8>Cavalerie lourde</option></select>&nbsp;Minimun : <input type=text size=5 value="0" id=BOApproMin></td></tr>';
  
  var Types = ['gold','food','wood','stone','iron','aetherstone'];
   
    m += '<TR align="left"><td colspan=2>Appro</td>';
   for (var y=0; y< Seed.cities.length;y++)
    m += '<td>'+Seed.cities[y][1]+'</td>';
   for (var i=0;i<=5;i++) {
    m += '</tr><tr><td align=center valign=middle rowspan=2><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/'+Types[i]+'_30.png"></td><td>'+uW.g_js_strings.commonstr.inventory+'</td>';
    for (var y=0; y< Seed.cities.length;y++)
     m += '<td><span id="ReappRec_'+y+'_'+i+'"></span></td>';
    m += '</tr><tr><td>Minimun &agrave; garder</td>';
        for (var y=0; y< Seed.cities.length;y++)
     m += '<td><input id="ReappRes_'+y+'_'+i+'" type=text size=10 maxlength=12 value=0></td>';  
    m +='</tr>';
   }
   m += '</table><br><u><b>Mode d\'emploi :</b></u><br>1. Cliquez sur votre GQ pour choissir votre ville stock (GQ)<br>2. Cliquez sur Valeurs AUTOMATIQUE : Veillez &agrave; ce que le transport automatique soit configur&eacute; OU<br>2. Remplissez la quantit&eacute; &agrave; garder sur vos villes secondaires (par exemple : 15M de mines et 15M de pierre)<br>3. Si l\'interval est &agrave; 0, merci de faire F5<br>4. Appuyez sur ON !!!';
   t.TransportDiv.innerHTML = m; 
   if (t.reapproState.city==undefined ||t.reapproState.city==-1) {
    
    t.reapproState.city=0;
   }
   ById('boaideappro').addEventListener('click', function(){
       	 window.open(sitesupport+"?page=aide_appro");
    	} , false);
   t.reacp = new CdispCityPicker ('botrader', ById('borescity'), true, t.updateResources2, t.reapproState.city);
   ById('BOApproMin').addEventListener('change', function(){
    t.reapproState.mini = ById('BOApproMin').value;
    t.saveReappro();
    }, false); 
   ById('boReapproState').addEventListener('click', function(){t.toggleReapproState(this);}, false);
   ById('boReappro').addEventListener('click', function(){t.saveReappro();}, false);
   
   ById('pbreapprointerval').addEventListener('keyup', function(){
      		if (isNaN(ById('pbreapprointerval').value)){ ById('pbreapprointerval').value=60 ;}
      		Options.reapprointerval = ById('pbreapprointerval').value;
      		saveOptions();
   }, false);
   
   ById('BORecupReappro').addEventListener('click', function(){t.RecupReappro();}, false);
   ById('BOApproUnit').value = t.reapproState.unit;
   ById('BOApproMin').value = parseIntNan(t.reapproState.mini);
   ById('BOApproUnit').addEventListener('change', function(){
    t.reapproState.unit = ById('BOApproUnit').value;
    t.saveReappro();
    
   }, false);
   
   t.updateResources2();
  },
  RecupReappro:function() {
   var t = Tabs.TranspAuto;
   var r = t.tradeRoutes;
   for (var y=0; y< Seed.cities.length;y++) {
    for (var i=0;i<(r.length);i++) {
     if (parseInt(Seed.cities[y][0]) == r[i].city) {
   ById('ReappRes_'+y+'_0').value=r[i].target_Gold;
   ById('ReappRes_'+y+'_1').value=r[i].target_Food;
   ById('ReappRes_'+y+'_2').value=r[i].target_Wood;
   ById('ReappRes_'+y+'_3').value=r[i].target_Stone;
   ById('ReappRes_'+y+'_4').value=r[i].target_Ore;
   ById('ReappRes_'+y+'_5').value=r[i].target_Astone;
   
     }
    } 
   }
   t.saveReappro();
   
   
  },
  saveReapproState: function(){
    var t = Tabs.TranspAuto;
    var serverID = getServerId();
    GM_setValue('reapproState_' + serverID, JSON2.stringify(t.reapproState));
  },
  saveReappro:function() {
   var t = Tabs.TranspAuto;
   for (var y=0; y< Seed.cities.length;y++) {
    t.reapproState['ReappRes_'+y+'_0'] = parseIntNan(ById('ReappRes_'+y+'_0').value);
    for (var i=1;i<=5;i++) {
     t.reapproState['ReappRes_'+y+'_'+i] = parseIntNan(ById('ReappRes_'+y+'_'+i).value);
    }
   }
   t.saveReapproState();
  },
  readReapproState: function(){
             var t = Tabs.TranspAuto;
             var serverID = getServerId();
             s = GM_getValue('reapproState_' + serverID);
             if (s != null) {
                 state = JSON2.parse(s);
                 for (k in state)
                     t.reapproState[k] = state[k];
             }
  },
  toggleReapproState: function(obj){
     	   var t = Tabs.TranspAuto;
     	   obj = ById('boReapproState');
             if (t.reapproState.running == true) {
                 t.reapproState.running = false;
                 if (obj)  obj.value = "Appro = OFF";
     	       updatebotbutton('Appro - OFF', 'boreapprotab');
     	      clearTimeout(t.checkdoreapprotimeout);
             }
             else {
                t.reapproState.running = true;
                if (obj) obj.value = "Appro = ON";
     		updatebotbutton('Appro - ON', 'boreapprotab');
     		t.actionreappro();
             }
  },
  retry:0,
  nbcity:-1,
  actionreappro:function() {
   var t = Tabs.TranspAuto;
   t.nbcity++;
   if (t.reapproState.running == false) {
     clearTimeout(t.checkdoreapprotimeout);
     return;
   }
   if (t.nbcity==t.reapproState.city)
   	t.nbcity++;  
   var tempsprochainevisite = 10000;
   if ((Seed.cities.length-1)<t.nbcity) {
    tempsprochainevisite = Options.reapprointerval*60*1000;
    t.nbcity=-1;
   } else {
     var besoin=[0,0,0,0,0,0]; 
     var stock=[0,0,0,0,0,0];
     qtemin = parseIntNan(t.reapproState['ReappRes_'+t.nbcity+'_0']);
     qtest = parseIntNan(Seed.citystats["city" + Seed.cities[t.nbcity][0]]['gold'][0]);
     if (qtest<qtemin)
        besoin[0] = parseInt(qtemin - qtest);
     stock[0] = parseIntNan(Seed.citystats["city" + Seed.cities[t.reapproState.city][0]]['gold'][0]);
     for (var i=1;i<=5;i++) {
        qtemin = parseIntNan(t.reapproState['ReappRes_'+t.nbcity+'_'+i]);
        if(i==5) {
         qtest = parseInt(Seed.resources["city" + Seed.cities[t.nbcity][0]]['rec'+i][0]);
         qtstock = parseInt(Seed.resources["city" + Seed.cities[t.reapproState.city][0]]['rec'+i][0]);
        }else {
         qtest = parseInt(Seed.resources["city" + Seed.cities[t.nbcity][0]]['rec'+i][0]/3600);
         qtstock= parseInt(Seed.resources["city" + Seed.cities[t.reapproState.city][0]]['rec'+i][0]/3600);
        }
        if (qtest<qtemin)
        besoin[i] = parseInt(qtemin - qtest);
        stock[i] = qtstock;
     }   
     var rallypointlevel = t.getRallypoint('city' + Cities.cities[t.reapproState.city].id);
     if(rallypointlevel == 12) rallypointlevel = 11;
     var slots = 0;
     var cityId = 'city'+ Cities.cities[t.reapproState.city].id;
     for (var k in Seed.queue_atkp[cityId]){   
         	         march = Seed.queue_atkp[cityId][k];
         	         if (typeof (march) == 'object'){
         	           slots++;
         	         }
     }
     if(slots >= rallypointlevel){
      		actionLog("Appro","Transport de "+Cities.cities[t.reapproState.city].name+" vers "+Cities.cities[t.nbcity].name+" <font color=red>Point de ralliement complet !</font>");
      		return;
     }
     if (besoin[0]>0 || besoin[1]>0|| besoin[2]>0 || besoin[3]>0 || besoin[4]>0 || besoin[5]>0) {
     //actionLog("Appro","Transport de "+Cities.cities[t.reapproState.city].name+" vers "+Cities.cities[t.nbcity].name+" : pierre:" + besoin[3] +"<"+stock[3]+" && mine: "+besoin[4]+"<"+stock[4]+"");
     if (besoin[0]<=stock[0] && besoin[1]<=stock[1] && besoin[2]<=stock[2] && besoin[3]<=stock[3] && besoin[4]<=stock[4] && besoin[5]<=stock[5]) {
          var unit = 'unt' + t.reapproState.unit
       	  Troops = parseInt(Seed.units['city' + Seed.cities[t.reapproState.city][0]][unit]);
       	     var untid=t.reapproState.unit;
	     var techLoadBoost=parseInt(Seed.tech.tch10)*0.1;
	     var loadEffectBoost=0;
	     if(Seed.playerEffects.loadExpire>uW.unixtime()){loadEffectBoost=0.25}
	     var loadBoostBase=(uW.cm.ThroneController.effectBonus(6)*0.01)+loadEffectBoost+techLoadBoost;
	     var loadBoost=loadBoostBase;
	     if(uW.cm.unitFrontendType[untid]=="siege"){
	      loadBoost+=(uW.cm.ThroneController.effectBonus(59)*0.01)
	     }else{
	      if(uW.cm.unitFrontendType[untid]=="horsed"){
	       loadBoost+=(uW.cm.ThroneController.effectBonus(48)*0.01)
	      }
   	 }
       	  var LoadUnit=parseInt(parseInt(uW.unitstats["unt"+untid][5])*(1+loadBoost));
       	  TroopsNeeded = (besoin[0] + besoin[1] + besoin[2] + besoin[3] + besoin[4] + (besoin[5]*5))  / LoadUnit;
       	  TroopsNeeded = TroopsNeeded.toFixed(0);
       	  if (TroopsNeeded < ((besoin[0] + besoin[1] + besoin[2] + besoin[3] + besoin[4] + (besoin[5]*5))  / LoadUnit )) TroopsNeeded++;
       	  var rallypointlevel = t.getRallypoint('city' +Seed.cities[t.reapproState.city][0]);	
  	  if (rallypointlevel == 11) rallypointlevel = 15;
	  if (rallypointlevel == 12) rallypointlevel = 20;
       	  if (parseInt(TroopsNeeded) > parseInt(rallypointlevel*10000)){ 
       	   TroopsNeeded = (rallypointlevel*10000); 
       	   var lemax=LoadUnit*TroopsNeeded;
       	   var totalb=lemax;
       	   for (var i=1;i<=5;i++) {
       	    if (besoin[i]>=totalb)
       	    	besoin[i]=totalb;
       	    totalb=totalb-besoin[i];
       	   }
       	  }
       	  if (parseIntNan(TroopsNeeded)<=parseIntNan(Troops) && parseIntNan(TroopsNeeded)>=parseIntNan(t.reapproState.mini)) { 
       	   var city = Seed.cities[t.reapproState.city][0]
       	   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
	   params.gold =besoin[0];
	   params.r1 =besoin[1];
	   params.r2 =besoin[2];
	   params.r3 =besoin[3];
	   params.r4 =besoin[4];
	   params.r5 =besoin[5];
   	   params.kid = 0;
   	   params.type = "1";
       	   params.cid=city;
       	   switch (unit){
	            case 'unt1': params.u1 = TroopsNeeded;break;
	            case 'unt2': params.u2 = TroopsNeeded;break;
	            case 'unt3': params.u3 = TroopsNeeded;break;
	            case 'unt4': params.u4 = TroopsNeeded;break;
	            case 'unt5': params.u5 = TroopsNeeded;break;
	            case 'unt6': params.u6 = TroopsNeeded;break;
	            case 'unt7': params.u7 = TroopsNeeded;break;
	            case 'unt8': params.u8 = TroopsNeeded;break;
	            case 'unt9': params.u9 = TroopsNeeded;break;
	            case 'unt10': params.u10 = TroopsNeeded;break;
	            case 'unt11': params.u11 = TroopsNeeded;break;
	            case 'unt12': params.u12 = TroopsNeeded;break;
           }
       	   params.xcoord = Seed.cities[t.nbcity][2];
   	   params.ycoord = Seed.cities[t.nbcity][3];
  
       	  new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
	                       method: "post",
	                       parameters: params,
	                       loading: true,
	                       onSuccess: function (transport) {
	                       var rslt = eval("(" + transport.responseText + ")");
	                       if (rslt.ok) {
	                       var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
	                       var ut = uW.unixtime();
	                       var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
	                       for(i = 0; i <= unitsarr.length; i++){
	                       	if(params["u"+i]){
	                       	unitsarr[i] = params["u"+i];
	                       	}
	                       }
	                       var resources=new Array();
	                       resources[0] = params.gold;
	                       for(i=1; i<=5; i++){
	                       	resources[i] = params["r"+i];
	                       }
	                       var currentcityid = city;
	                       uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
	                       uW.update_seed(rslt.updateSeed)
	                       if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
	                        actionLog("Appro","Transport de "+Cities.cities[t.reapproState.city].name+" vers "+Cities.cities[t.nbcity].name+" de "+TroopsNeeded+" "+uW.unitcost[unit][0]);
	                       } else {
	  			actionLog("Appro","Transport de "+Cities.cities[t.reapproState.city].name+" vers "+Cities.cities[t.nbcity].name+" <font color=red>" + transport.responseText +"</font>");
	  			t.retry++;
	  			if (t.retry>4) {
	  			 t.retry=0;
	  			}else {
	  			 setTimeout(function() {t.nbcity--;t.actionreappro();},4000);
	  			}
	                       }
	                       },
	                       onFailure: function (rslt) {actionLog("Appro","<font color=red>" + rslt.responseText +"</font>");}
             });          	  
       	  } else {
       	   actionLog("Appro","Transport de "+Cities.cities[t.reapproState.city].name+" vers "+Cities.cities[t.nbcity].name+" : blocage troupes minimun");
       	  }
      } else {
       actionLog("Appro","Transport de "+Cities.cities[t.reapproState.city].name+" vers "+Cities.cities[t.nbcity].name+" : Stock insuffisant");
      }
     }
   }
   t.checkdoreapprotimeout = setTimeout(function() { t.actionreappro();}, tempsprochainevisite);
  },
  showAuto: function() {
   var t = Tabs.TranspAuto;
    var m = '<DIV id=pbTowrtDivF class=boStat>TRANSPORT AUTOMATIQUE - CONFIGURATION</div><TABLE id=pbtraderfunctions width=100% height=0% class=pbTab><TR align="center">';
         if (t.traderState.running == false) {
             m += '<TD><INPUT id=pbTraderState type=submit value="Transport = OFF"></td>';
   	       updatebotbutton('Transp - OFF', 'pbtrantab');
         } else {
             m += '<TD><INPUT id=pbTraderState type=submit value="Transport = ON"></td>';
   	      updatebotbutton('Transp - ON', 'pbtrantab');
         }
         m += '<TD><INPUT id=pbShowRoutes type=submit value="Voir les Routes"></td>';
         m += '</tr></table></div>';
         m += '<DIV id=pbTraderDivDRoute class=boStat>OPTIONS DU TRANSPORT</div>';
         m += '<TABLE id=pbtraderfunctions width=100% height=0% class=pbTab><TR align="left">';
   	 m += '<TD colspan=2>Envoyer les transports toutes les <INPUT id=pbtransportinterval type=text size=4 value="'+Options.transportinterval+'"\> minutes</td>';
         m += '<TD colspan=4>Envoyer les transports avec un minumum de <INPUT id=pbminwagons type=text size=2 value="'+Options.minwagons+'"\> unit&eacute;s.</td></tr></table>';
         m += '</table>';
         m += '<DIV id=pbTraderDivDRoute class=boStat>AJOUTER UN TRANSPORT</div>';
         m += '<TABLE id=pbaddtraderoute width=95% height=0% class=pbTab><TR align="left">';
         m += '<TR align="left"><TD>Source :</td> <TD colspan=4><DIV style="margin-bottom:10px;"><span id=ptrescity></span></div></td></tr>';
   
         m += '<TR align="left">';
         m += '<TD>Destination :</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptcityTo></span></div></td>';
         m += '<TD>OU</td>';
         m += '<TD>X:<INPUT id=ptcityX type=text size=3\></td>';
         m += '<TD>Y:<INPUT id=ptcityY type=text size=3\></td></tr>';
         m += '<TABLE id=pbaddtraderoute height=0% class=pbTab><TR align="left">';
         m += '<TD width=75px>'+uW.g_js_strings.commonstr.troops+' :</td><TD width=150px><SELECT id="TransportTroop">';
         for (y in uW.unitcost) m+='<option value="'+y+'">'+unsafeWindow.unitcost[y][0]+'</option>';
         m+='</select></td><TD width=75px>Dispo :&nbsp;</td><TD id=TroopAmount align=left width=75px></td>';
         m+='<TD width=75px>Estimation ::&nbsp;</td><TD id=CarryAmount align=left width=75px></td>';
         m += '<TR><TD >Troops: </td><TD><INPUT id=TroopsToSend type=text size=6 maxlength=6 value="0">&nbsp;&nbsp;<INPUT id=MaxTroops type=submit value="Max"></td>';
         m += '<TD width=50px><INPUT id=FillInMax type=submit value="<----"></td>';
         m +='<TD id=Calc colspan=3></td></tr>';
         m += '<TABLE id=pbaddtraderoute height=0% class=pbTab><TR align="center">';
         m += '<TD width=5%><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png"></td>';
         m += '<TD id=TransRec1 align=right width=110px></td>';
         m += '<TD id=HaveRec1 align=right width=110px></td>';
         m += '<TD width=55px align=right><INPUT id=pbshipFood type=checkbox unchecked=true\></td>';
         m += '<TD width=180px  align=left>Garder : <INPUT id=pbtargetamountFood type=text size=11 maxlength=12 value="0" disabled=true\></td>';
         m += '<TD width=100px>Transporter: <INPUT id=pbtradeamountFood type=text size=11 maxlength=12 value="0"\></td>';
         m += '<TD width=50px><INPUT id=MaxFood type=submit value="Max"></td></tr>';
         m += '<TR align="center">';
         m += '<TD width=5%><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png"></td>';
         m += '<TD id=TransRec2 align=right width=110px></td>';
         m += '<TD id=HaveRec2 align=right width=110px></td>';
         m += '<TD width=55px align=right><INPUT id=pbshipWood type=checkbox unchecked=true\></td>';
         m += '<TD width=180px align=left>Garder : <INPUT id=pbtargetamountWood type=text size=11 maxlength=12 value="0" disabled=true\></td>';
         m += '<TD width=100px>Transporter: <INPUT id=pbtradeamountWood type=text size=11 maxlength=12 value="0"\></td>';
         m += '<TD width=50px><INPUT id=MaxWood type=submit value="Max"></td></tr>';
         m += '<TR align="center">';
         m += '<TD width=5%><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png"></td>';
         m += '<TD id=TransRec3 align=right width=110px></td>';
         m += '<TD id=HaveRec3 align=right width=110px></td>';
         m += '<TD width=55px align=right><INPUT id=pbshipStone type=checkbox unchecked=true\></td>';
         m += '<TD width=180px align=left>Garder : <INPUT id=pbtargetamountStone type=text size=11 maxlength=12 value="0" disabled=true\></td>';
         m += '<TD width=100px>Transporter: <INPUT id=pbtradeamountStone type=text size=11 maxlength=12 value="0"\></td>';
         m += '<TD width=50px><INPUT id=MaxStone type=submit value="Max"></td></tr>';
         m += '<TR align="center">';
         m += '<TD width=5%><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png"></td>';
         m += '<TD id=TransRec4 align=right width=110px></td>';
         m += '<TD id=HaveRec4 align=right width=110px></td>';
         m += '<TD width=55px align=right><INPUT id=pbshipOre type=checkbox unchecked=true\></td>';
         m += '<TD width=180px align=left>Garder : <INPUT id=pbtargetamountOre type=text size=11 maxlength=12 value="0" disabled=true\></td>';
         m += '<TD width=100px>Transporter: <INPUT id=pbtradeamountOre type=text size=11 maxlength=12 value="0"\></td>';
         m += '<TD width=50px><INPUT id=MaxOre type=submit value="Max"></td></tr>';
          m += '<TR align="center">';
      m += '<TD width=5%><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png"></td>';
      m += '<TD id=TransRec5 align=right width=110px></td>';
      m += '<TD id=HaveRec5 align=right width=110px></td>';
      m += '<TD width=55px align=right><INPUT id=pbshipAstone type=checkbox unchecked=true\></td>';
      m += '<TD width=180px align=left>Garder : <INPUT id=pbtargetamountAstone type=text size=11 maxlength=12 value="0" disabled=true\></td>';
      m += '<TD width=100px>Transporter: <INPUT id=pbtradeamountAstone type=text size=11 maxlength=12 value="0"\></td>';
      m += '<TD width=50px><INPUT id=MaxAstone type=submit value="Max"></td></tr>';
      m += '<TR align="center">';
         m += '<TD width=5%><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_30.png"></td>';
         m += '<TD id=TransGold align=right width=110px></td>';
         m += '<TD id=HaveGold align=right width=110px></td>';
         m += '<TD width=55px align=right><INPUT id=pbshipGold type=checkbox unchecked=true\></td>';
         m += '<TD width=180px align=left>Garder : <INPUT id=pbtargetamountGold type=text size=11 maxlength=12 value="0" disabled=true\></td>';
         m += '<TD width=100px>Transporter: <INPUT id=pbtradeamountGold type=text size=11 maxlength=12 value="0"\></td>';
         m += '<TD width=50px><INPUT id=MaxGold type=submit value="Max"></td></tr>';
   
         m += '</table>';
   
         m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRoute type=submit value="Ajouter une Route"><INPUT id=pbManualSend type=submit value="Transport Manuel"></div>';
         m += '<DIV id=errorSpace></div>'
      
  	 t.TransportDiv.innerHTML = m; 
   
    ById('TransportTroop').value = 'unt9';
         
         t.tcp = new CdispCityPicker ('pttrader', ById('ptrescity'), true, t.updateResources, 0);
         t.tcpto = new CdispCityPicker ('pttraderTo', ById('ptcityTo'), true, t.clickCitySelect).bindToXYboxes(document.getElementById ('ptcityX'), document.getElementById ('ptcityY'));
         
         
       ById('TransportTroop').addEventListener('change', function(){t.updateTroops();}, false);
         ById('pbTraderState').addEventListener('click', function(){t.toggleTraderState(this);}, false);
         ById('pbSaveRoute').addEventListener('click', function(){t.addTradeRoute();}, false);
         ById('pbManualSend').addEventListener('click', function(){t.ManualTransport();}, false);
         ById('pbShowRoutes').addEventListener('click', function(){t.showTradeRoutes();}, false);
         ById('FillInMax').addEventListener('click', function(){ById('TroopsToSend').value = t.TroopsNeeded;}, false);
         
         ById('MaxTroops').addEventListener('click', function(){
   			var rallypointlevel = t.getRallypoint('city' + t.tcp.city.id);
   			if (rallypointlevel == 11) rallypointlevel = 15;
   			if (rallypointlevel == 12) rallypointlevel = 20;
   			var max = t.Troops;
   			if (t.Troops > (rallypointlevel*10000) ) max = (rallypointlevel*10000);
   			ById('TroopsToSend').value = max;
   	  }, false);
         ById('MaxFood').addEventListener('click', function(){
         		t.Food = 0;
   			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
         		ById('pbtradeamountFood').value = (parseInt(input) <= parseIntCommas(ById('TransRec1').innerHTML))?input:parseIntCommas(ById('TransRec1').innerHTML);
         }, false);
         ById('MaxWood').addEventListener('click', function(){
         		t.Wood = 0;
   			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
         		ById('pbtradeamountWood').value = (parseInt(input) <= parseIntCommas(ById('TransRec2').innerHTML))?input:parseIntCommas(ById('TransRec2').innerHTML);
         }, false);
         ById('MaxStone').addEventListener('click', function(){
         		t.Stone = 0;
   			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
         		ById('pbtradeamountStone').value = (parseInt(input) <= parseIntCommas(ById('TransRec3').innerHTML))?input:parseIntCommas(ById('TransRec3').innerHTML);
         }, false);
         ById('MaxOre').addEventListener('click', function(){
         		t.Ore = 0;
   			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
         		ById('pbtradeamountOre').value = (parseInt(input) <= parseIntCommas(ById('TransRec4').innerHTML))?input:parseIntCommas(ById('TransRec4').innerHTML);
         }, false);
         ById('MaxGold').addEventListener('click', function(){
   			t.Gold = 0;
   			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
         		ById('pbtradeamountGold').value = (parseInt(input) <= parseIntCommas(ById('TransGold').innerHTML))?input:parseIntCommas(ById('TransGold').innerHTML);
         }, false);
   	   ById('MaxAstone').addEventListener('click', function(){
         		t.Astone = 0;
   			var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
         		ById('pbtradeamountAstone').value = (parseInt(input) <= parseIntCommas(ById('TransRec5').innerHTML))?input:parseIntCommas(ById('TransRec5').innerHTML);
         }, false);
         
         ById('pbtransportinterval').addEventListener('keyup', function(){
   		if (isNaN(ById('pbtransportinterval').value)){ ById('pbtransportinterval').value=60 ;}
   		Options.transportinterval = ById('pbtransportinterval').value;
   		saveOptions();
         }, false);
         
         ById('pbtargetamountFood').addEventListener('keyup', function(){
             if (isNaN(ById('pbtargetamountFood').value)) ById('pbtargetamountFood').value=0 ;
         }, false);
         ById('pbtargetamountWood').addEventListener('keyup', function(){
             if (isNaN(ById('pbtargetamountWood').value)) ById('pbtargetamountWood').value=0 ;
         }, false);
         ById('pbtargetamountStone').addEventListener('keyup', function(){
             if (isNaN(ById('pbtargetamountStone').value)) ById('pbtargetamountStone').value=0 ;
         }, false);
         ById('pbtargetamountOre').addEventListener('keyup', function(){
             if (isNaN(ById('pbtargetamountOre').value)) ById('pbtargetamountOre').value=0 ;
         }, false);
   	  ById('pbtargetamountAstone').addEventListener('keyup', function(){
             if (isNaN(ById('pbtargetamountAstone').value)) ById('pbtargetamountAstone').value=0 ;
         }, false);
         ById('pbtargetamountGold').addEventListener('keyup', function(){
             if (isNaN(ById('pbtargetamountGold').value)) ById('pbtargetamountGold').value=0 ;
         }, false);
         ById('pbtradeamountFood').addEventListener('keyup', function(){
             if (isNaN(ById('pbtradeamountFood').value)) ById('pbtradeamountFood').value=0 ;
         }, false);
         ById('pbtradeamountWood').addEventListener('keyup', function(){
             if (isNaN(ById('pbtradeamountWood').value)) ById('pbtradeamountWood').value=0 ;
         }, false);
         ById('pbtradeamountStone').addEventListener('keyup', function(){
             if (isNaN(ById('pbtradeamountStone').value)) ById('pbtradeamountStone').value=0 ;
         }, false);
         ById('pbtradeamountOre').addEventListener('keyup', function(){
             if (isNaN(ById('pbtradeamountOre').value)) ById('pbtradeamountOre').value=0 ;
         }, false);
   	  ById('pbtradeamountAstone').addEventListener('keyup', function(){
             if (isNaN(ById('pbtradeamountAstone').value)) ById('pbtradeamountAstone').value=0 ;
         }, false);
         ById('pbtradeamountGold').addEventListener('keyup', function(){
             if (isNaN(ById('pbtradeamountGold').value)) ById('pbtradeamountGold').value=0 ;
         }, false);
        ById('pbminwagons').addEventListener('keyup', function(){
            if (isNaN(ById('pbminwagons').value)) ById('pbminwagons').value=100 ;
            Options.minwagons = parseInt(ById('pbminwagons').value);
            saveOptions();
        }, false)
         
         ById('pbshipFood').addEventListener('click', function(){
             if (ById('pbshipFood').checked==false) {
                 ById('pbtargetamountFood').disabled = true;
             }
             else {
               ById('pbtargetamountFood').disabled = false;
             }
         },false);
         ById('pbshipWood').addEventListener('click', function(){
             if (ById('pbshipWood').checked==false) {
                 ById('pbtargetamountWood').disabled = true;
             }
             else {
               ById('pbtargetamountWood').disabled = false;
             }
         },false);
         ById('pbshipStone').addEventListener('click', function(){
             if (ById('pbshipStone').checked==false) {
                 ById('pbtargetamountStone').disabled = true;
             }
             else {
               ById('pbtargetamountStone').disabled = false;
             }
         },false);
         ById('pbshipOre').addEventListener('click', function(){
             if (ById('pbshipOre').checked==false) {
                 ById('pbtargetamountOre').disabled = true;
             }
             else {
               ById('pbtargetamountOre').disabled = false;
             }
         },false);
   	   ById('pbshipAstone').addEventListener('click', function(){
             if (ById('pbshipAstone').checked==false) {
                 ById('pbtargetamountAstone').disabled = true;
             }
             else {
               ById('pbtargetamountAstone').disabled = false;
             } 
         },false);
          ById('pbshipGold').addEventListener('click', function(){
             if (ById('pbshipGold').checked==false) {
                 ById('pbtargetamountGold').disabled = true;
             }
             else {
               ById('pbtargetamountGold').disabled = false;
             }
         },false);
  
       },
       updateResources2 : function (){
       var t = Tabs.TranspAuto
       t.reapproState.city = t.reacp.city.idx;
       for (var y=0; y< Seed.cities.length;y++) {
         if (t.reacp.city.id==Seed.cities[y][0]) {
          ById('ReappRes_'+y+'_0').value="0";
          ById('ReappRes_'+y+'_0').disabled=true;
         }else {
          ById('ReappRes_'+y+'_0').disabled=false;
          ById('ReappRes_'+y+'_0').value=parseIntNan(t.reapproState['ReappRes_'+y+'_0']);
          ById('ReappRec_'+y+'_0').innerHTML = addCommas ( parseIntNan(Seed.citystats["city" + Seed.cities[y][0]]['gold'][0]) );
          }
         for (var i=1;i<=5;i++) {
          if (t.reacp.city.id==Seed.cities[y][0]) {
            ById('ReappRes_'+y+'_'+i).value="0";
            ById('ReappRes_'+y+'_'+i).disabled=true;
          } else{
            ById('ReappRes_'+y+'_'+i).value= parseIntNan(t.reapproState['ReappRes_'+y+'_'+i]);
            ById('ReappRes_'+y+'_'+i).disabled=false;
          }
          if(i==5)
              ById('ReappRec_'+y+'_'+i).innerHTML = addCommas ( parseIntNan(Seed.resources["city" + Seed.cities[y][0]]['rec'+i][0]) );
          else 
              ById('ReappRec_'+y+'_'+i).innerHTML = addCommas ( parseIntNan(Seed.resources["city" + Seed.cities[y][0]]['rec'+i][0]/3600));    
         }
        
       }
       
       },
       updateResources : function (){
       	var t = Tabs.TranspAuto
       	var ToCity = null;
       	for (var i=1;i<=5;i++)
   			if(i==5)
   			   ById('TransRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + t.tcp.city.id]['rec'+i][0]) );
   			else 
                          ById('TransRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + t.tcp.city.id]['rec'+i][0]/3600) );
       	ById('TransGold').innerHTML = addCommas ( parseInt(Seed.citystats["city" + t.tcp.city.id]['gold'][0]) );
       	for (ii in Seed.cities)
           if (Seed.cities[ii][2] == document.getElementById ('ptcityX').value && Seed.cities[ii][3] == document.getElementById ('ptcityY').value)
             ToCity = Seed.cities[ii][0];
         for (var i=1;i<=5;i++)
             if (ToCity != null)
   			if(i==5)
   			   ById('HaveRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + ToCity]['rec'+i][0]) );
   			else
                  ById('HaveRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + ToCity]['rec'+i][0]/3600) );
       	  else ById('HaveRec'+i).innerHTML = "----";
         if (ToCity != null) ById('HaveGold').innerHTML = addCommas ( parseInt(Seed.citystats["city" + ToCity]['gold'][0]) );
         else  ById('HaveGold').innerHTML =  "----";   
       },
       
       updateTroops : function (city){
       	var t = Tabs.TranspAuto;
       	var fontcolor = 'black';
       	t.Food = parseInt(ById('pbtradeamountFood').value);
         	t.Wood = parseInt(ById('pbtradeamountWood').value);
         	t.Stone = parseInt(ById('pbtradeamountStone').value);
         	t.Ore = parseInt(ById('pbtradeamountOre').value);
         	t.Gold = parseInt(ById('pbtradeamountGold').value);
   		t.Astone = parseInt(ById('pbtradeamountAstone').value*5);
       	var unit = ById('TransportTroop').value;
       	t.Troops = parseInt(Seed.units['city' + t.tcp.city.id][unit]);
      	var untid=ById('TransportTroop').value;
	var techLoadBoost=parseInt(Seed.tech.tch10)*0.1;
	var loadEffectBoost=0;
	 if(Seed.playerEffects.loadExpire>uW.unixtime()){loadEffectBoost=0.25}
		     var loadBoostBase=(uW.cm.ThroneController.effectBonus(6)*0.01)+loadEffectBoost+techLoadBoost;
		     var loadBoost=loadBoostBase;
		     if(uW.cm.unitFrontendType[untid]=="siege"){
		      loadBoost+=(uW.cm.ThroneController.effectBonus(59)*0.01)
		     }else{
		      if(uW.cm.unitFrontendType[untid]=="horsed"){
		       loadBoost+=(uW.cm.ThroneController.effectBonus(48)*0.01)
		      }
	 }
        var LoadUnit=parseInt(parseInt(uW.unitstats[untid][5])*(1+loadBoost));
       	var GlobalMaxLoad = t.Troops * LoadUnit;
       	t.MaxLoad = parseInt(ById('TroopsToSend').value) * LoadUnit;
        	t.TroopsNeeded = (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) / LoadUnit;
        	t.TroopsNeeded = t.TroopsNeeded.toFixed(0);	
   		if (t.TroopsNeeded < ((t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) / LoadUnit)) t.TroopsNeeded++;	
           
           if ( t.TroopsNeeded > t.Troops) fontcolor = 'red';
       	if (t.Troops > 0 ) ById('TroopAmount').innerHTML = '<FONT color='+fontcolor+'>' + addCommas(t.Troops) + '</font>';
       	else ById('TroopAmount').innerHTML = 0;
       	if (GlobalMaxLoad > 0) ById('CarryAmount').innerHTML = addCommas(GlobalMaxLoad);
       	else  ById('CarryAmount').innerHTML = 0;
       	ById('Calc').innerHTML = 'Ressources: ' +  addCommas(t.Food + t.Wood + t.Stone + t.Ore + t.Gold  + t.Astone) + ' / ' + addCommas(t.MaxLoad) + '&nbsp;&nbsp;(Troupes n&eacute;cessaires : <FONT color='+fontcolor+'>' + addCommas(t.TroopsNeeded) + '</font> )' ;
       },    
       getRallypoint: function(cityId){
         var t = Tabs.TranspAuto;
         for (var o in Seed.buildings[cityId]){
   		var buildingType = parseInt(Seed.buildings[cityId][o][0]);
   		var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
   		if (buildingType == 12){
   			return parseInt(buildingLevel);
   			break;
   		}
   	   }
   	  return 0;
       },
      e_tradeRoutes: function(){
         var t = Tabs.TranspAuto;
         var now = new Date();
         if (t.traderState.running == true)    {
         	var now = new Date().getTime()/1000.0;
         	now = now.toFixed(0);
         	var last = Options.lasttransport;
          		if ( now > (parseInt(last) + (Options.transportinterval*60))){
   				  t.checkdoTrades();
         		}
         }
   	  setTimeout(function(){ t.e_tradeRoutes();}, Options.transportinterval*1000);
   	  
       },
       	
   	delTradeRoutes: function() {
   		var t = Tabs.TranspAuto;	
   		t.tradeRoutes= [];
   	},
   	
   	checkcoords : function (obj){
   		var t = Tabs.TranspAuto;
   		if(obj.id == 'pbok'){
   			t.check = true;
   			t.addTradeRoute();
   		}
   		return;			
   	},
   	
   	addTradeRoute: function () {
   		var valid = true;
   		var t = Tabs.TranspAuto;
   		var city = t.tcp.city.id;
   		if (ById('ptcityX').value==0 && ById('ptcityY').value ==0 && !t.check)
   		{
   			return;
   		}
   		var ship_Food = ById('pbshipFood').checked;
   		var ship_Wood = ById('pbshipWood').checked;
   		var ship_Stone = ById('pbshipStone').checked;
   		var ship_Ore = ById('pbshipOre').checked;
   		var ship_Astone = ById('pbshipAstone').checked;
   		var ship_Gold = ById('pbshipGold').checked;
   		var target_Food = ById('pbtargetamountFood').value;
   		var target_Wood = ById('pbtargetamountWood').value;
   		var target_Stone = ById('pbtargetamountStone').value;
   		var target_Ore = ById('pbtargetamountOre').value;
   		var target_Astone = ById('pbtargetamountAstone').value;
   		var target_Gold = ById('pbtargetamountGold').value;
   		var trade_Food = ById('pbtradeamountFood').value;
   		var trade_Wood = ById('pbtradeamountWood').value;
   		var trade_Stone = ById('pbtradeamountStone').value;
   		var trade_Ore = ById('pbtradeamountOre').value;
   		var trade_Astone = ById('pbtradeamountAstone').value;
   		var trade_Gold = ById('pbtradeamountGold').value;
   		var target_x = ById('ptcityX').value;
   		var target_y = ById('ptcityY').value;
   		var TroopType = ById('TransportTroop').value;
   		var route_state = true;
   				
   		if (valid == true) {
   			var lTR = t.tradeRoutes;
   			lTR.push({
   				city:				city,
   				ship_Food:			ship_Food,
   				target_Food:		target_Food,
   				trade_Food: 		trade_Food,
   				ship_Wood:			ship_Wood,
   				target_Wood:		target_Wood,
   				trade_Wood: 		trade_Wood,
   				ship_Stone:			ship_Stone,
   				target_Stone:		target_Stone,
   				trade_Stone: 		trade_Stone,
   				ship_Ore:			ship_Ore,
   				target_Ore:			target_Ore,
   				trade_Ore:	 		trade_Ore,
   				ship_Astone:	    ship_Astone,
   				target_Astone:		target_Astone,
   				trade_Astone:	 	trade_Astone,
   				ship_Gold:			ship_Gold,
   				target_Gold:		target_Gold,
   				trade_Gold: 		trade_Gold,
   				target_x: 			target_x,
   				target_y: 			target_y,
   				TroopType:      TroopType,
   				route_state: 		"true"
   			});
   		}
   		ById('pbTraderDivDRoute').style.background ='#99FF99';
   		setTimeout(function(){ (ById('pbTraderDivDRoute').style.background =''); }, 500);
   	},
   	showTradeRoutes: function () {
   		var t = Tabs.TranspAuto;
   		if (t.popTradeRoutes == null) {
   		 t.popTradeRoutes = new CPopup('pbShowTrade', 0, 0, 750, 500, true, function() {clearTimeout (1000);});
   		 t.popTradeRoutes.centerMe (mainPop.getMainDiv());
   		}
   		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbTab" id="pbRoutesQueue">';       
   		t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
   		t.popTradeRoutes.getTopDiv().innerHTML = '<TD><B>Les routes du Transport Automatique : </td>';
   		t.paintTradeRoutes();
   		t.popTradeRoutes.show(true)	;
   	},
   	paintTradeRoutes: function(){
   	        var t = Tabs.TranspAuto;
   	        var r = t.tradeRoutes;
   	        var cityname;
   	        var citynameTo = null;
   	    var m= '<TABLE id=paintRoutes class=pbTab>'; 
   			for (var i=0;i<(r.length);i++) {
   			  citynameTo = null;
   				for (var y=0; y< Seed.cities.length;y++) {
   					if ( parseInt(Seed.cities[y][0]) == r[i].city) var cityname = Seed.cities[y][1];
   					if ( parseInt(Seed.cities[y][2]) == r[i].target_x && parseInt(Seed.cities[y][3]) == r[i].target_y) var citynameTo = Seed.cities[y][1];
   				}    
   				var queueId = i;
   				if (citynameTo == null) var TO = r[i].target_x +','+ r[i].target_y;
   				else TO = citynameTo;
   				if (r[i].route_state) var status = '<FONT color=green>Activ&eacute;</font>';
   				else var status = '<FONT color=red>D&acture;activ&eacute;</font>';
   				if (r[i].TroopType == undefined) var unit = 'unt9';
           else var unit = r[i].TroopType;
   				m += '<TR><TD TD width=12px>&nbsp;&nbsp;</td></tr>';
           m +='<TR><TD width=20px>'+(i+1)+'</td><TD width=175px>Depuis:&nbsp;&nbsp;'+ cityname +'</TD><TD width=175px>Vers:&nbsp;&nbsp;'+ TO +'</td><TD width=175px>'+status+'</td>';
           m +='<TD width=60px><A onclick="traceEdit('+queueId+')">Editer</a></td><TD width=60px><A onclick="traceDelete('+queueId+')">Supprimer</a></td></tr>';
           m += '<TR><TD></td><TD>Troops:&nbsp;&nbsp;'+unsafeWindow.unitcost[unit][0]+'</td></tr>';
           if (r[i].ship_Food) m += '<TR><TD></td><TD align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png"></td><TD>Target: '+ addCommas(r[i].target_Food) +'</td><TD>Trade: '+ addCommas(r[i].trade_Food)+'</td>';
   				if (r[i].ship_Wood) m += '<TR><TD></td><TD align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png"></td><TD>Target: '+ addCommas(r[i].target_Wood) +'</td><TD>Trade: '+ addCommas(r[i].trade_Wood)+'</td>';
   				if (r[i].ship_Stone) m += '<TR><TD></td><TD align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png"></td><TD>Target: '+ addCommas(r[i].target_Stone) +'</td><TD>Trade: '+ addCommas(r[i].trade_Stone)+'</td>';
   				if (r[i].ship_Ore) m += '<TR><TD></td><TD align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png"></td><TD>Target: '+ addCommas(r[i].target_Ore) +'</td><TD>Trade: '+ addCommas(r[i].trade_Ore)+'</td>';
   				if (r[i].ship_Astone) m += '<TR><TD></td><TD align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png"></td><TD>Target: '+ addCommas(r[i].target_Astone) +'</td><TD>Trade: '+ addCommas(r[i].trade_Astone)+'</td>';
   				if (r[i].ship_Gold) m += '<TR><TD></td><TD align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_30.png"></td><TD>Target: '+ addCommas(r[i].target_Gold) +'</td><TD>Trade: '+ addCommas(r[i].trade_Gold)+'</td>';
          }
   	     m +='</table>';
   	     ById('pbRoutesQueue').innerHTML= m; 
          unsafeWindow.traceEdit = t.editQueueElement;
          unsafeWindow.traceDelete = t.cancelQueueElement;
   	    },
   	  
   	 cancelQueueElement: function(queueId){
   	     var t = Tabs.TranspAuto;
   	     var queueId = parseInt(queueId);
   	     t.tradeRoutes.splice(queueId, 1);
   	     t.showTradeRoutes();
   	 },
   	 
   	 editQueueElement: function(queueId){
   	     var t = Tabs.TranspAuto;
   	     var r = t.tradeRoutes;
          var queueId = parseInt(queueId);
   	     var cityname;
   	     var citynameTo = null;
   	     var Types = ['food','wood','stone','iron','aetherstone','gold'];
   	     for (var y=0; y< Seed.cities.length;y++) {
   					if ( parseInt(Seed.cities[y][0]) == r[queueId].city) var cityname = Seed.cities[y][1];
   					if ( parseInt(Seed.cities[y][2]) == r[queueId].target_x && parseInt(Seed.cities[y][3]) == r[queueId].target_y) var citynameTo = Seed.cities[y][1];
   			 }
          if (citynameTo == null) var TO = r[queueId].target_x +','+ r[queueId].target_y;
   			 else TO = citynameTo; 
          var n = '<TABLE id=editRoutes class=pbTab>';
   	     n +='<TD>Depuis :&nbsp;'+ cityname +'</td><TD>Vers :&nbsp;'+ TO +'</td>';
   	     n +='<TD><INPUT id=TradeStatus type=checkbox>&nbsp;Activ&eacute; la route</td>';
   	     n += '<TD width=150px>'+uW.g_js_strings.commonstr.troops+' :<SELECT id="pbbTransportTroop">';
          for (y in unsafeWindow.unitcost) n+='<option value="'+y+'">'+unsafeWindow.unitcost[y][0]+'</option>';
          n+='</select></td></table><BR><TABLE  id=editRoutes class=pbTab>';
          for (var i=0;i<Types.length;i++){
   	    var icon = Types[i];
            n += '<TR><TD width=50px align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/'+icon+'_30.png"></td>';
            n += '<TD width=50px align=center><INPUT id=pbbship'+Types[i]+' type=checkbox></td>';
            n += '<TD width=125px>Garde : <INPUT id=pbbtargetamount'+Types[i]+' type=text size=11 maxlength=12 value="0"></td>';
            n += '<TD width=125px>Transporte : <INPUT id=pbbtradeamount'+Types[i]+' type=text size=11 maxlength=12 value="0"\></td></tr>';
          }
          n+='</table><BR><TABLE id=editRoutes class=pbTab><TR><TD><a class="button20" id="Cancel"><span>'+uW.g_js_strings.commonstr.cancel+'</span></a></td>';
          n+='<TD><a class="button20" id="Save"><span>Enregistrer</span></a></td></tr>';
          n +='</table>';
          
          ById('pbRoutesQueue').innerHTML= n;
          ById('TradeStatus').checked = r[queueId].route_state;
          if (r[queueId].TroopType == undefined) var unit = 'unt9';
          else var unit = r[queueId].TroopType;
          ById('pbbTransportTroop').value = unit;
	         ById('pbbshipfood').checked = r[queueId].ship_Food;
	         ById('pbbshipwood').checked = r[queueId].ship_Wood;
	         ById('pbbshipstone').checked = r[queueId].ship_Stone;
	         ById('pbbshipiron').checked = r[queueId].ship_Ore;
	  	   ById('pbbshipaetherstone').checked = r[queueId].ship_Astone;
	         ById('pbbshipgold').checked = r[queueId].ship_Gold;
	         ById('pbbtargetamountfood').value = r[queueId].target_Food;
	         ById('pbbtargetamountwood').value = r[queueId].target_Wood;
	         ById('pbbtargetamountstone').value = r[queueId].target_Stone;
	         ById('pbbtargetamountiron').value = r[queueId].target_Ore;
	  	   ById('pbbtargetamountaetherstone').value = r[queueId].target_Astone;
	         ById('pbbtargetamountgold').value = r[queueId].target_Gold;
	         ById('pbbtradeamountfood').value = r[queueId].trade_Food;
	         ById('pbbtradeamountwood').value = r[queueId].trade_Wood;
	         ById('pbbtradeamountstone').value = r[queueId].trade_Stone;
	         ById('pbbtradeamountiron').value = r[queueId].trade_Ore;
	  	   ById('pbbtradeamountaetherstone').value = r[queueId].trade_Astone;
	         ById('pbbtradeamountgold').value = r[queueId].trade_Gold;
	         ById('Cancel').addEventListener('click', function(){t.showTradeRoutes();}, false);
	         ById('Save').addEventListener('click', function(){
	              r[queueId].route_state = ById('TradeStatus').checked;
	              r[queueId].TroopType = ById('pbbTransportTroop').value;
	              r[queueId].ship_Food = ById('pbbshipfood').checked;
	              r[queueId].ship_Wood = ById('pbbshipwood').checked;
	              r[queueId].ship_Stone = ById('pbbshipstone').checked;
	              r[queueId].ship_Ore = ById('pbbshipiron').checked;
	  			r[queueId].ship_Astone = ById('pbbshipaetherstone').checked;
	              r[queueId].ship_Gold = ById('pbbshipgold').checked;
	              r[queueId].target_Food = ById('pbbtargetamountfood').value;
	              r[queueId].target_Wood = ById('pbbtargetamountwood').value;
	              r[queueId].target_Stone = ById('pbbtargetamountstone').value;
	              r[queueId].target_Ore = ById('pbbtargetamountiron').value;
	  			r[queueId].target_Astone = ById('pbbtargetamountaetherstone').value;
	              r[queueId].target_Gold = ById('pbbtargetamountgold').value;
	              r[queueId].trade_Food = ById('pbbtradeamountfood').value;
	              r[queueId].trade_Wood = ById('pbbtradeamountwood').value;
	              r[queueId].trade_Stone = ById('pbbtradeamountstone').value;
	              r[queueId].trade_Ore = ById('pbbtradeamountiron').value;
	  			r[queueId].trade_Astone = ById('pbbtradeamountaetherstone').value;
	              r[queueId].trade_Gold = ById('pbbtradeamountgold').value;
	              t.showTradeRoutes();
	          }, false);
	 },
   	   
   	saveTradeRoutes: function(){
   		var t = Tabs.TranspAuto;
           var serverID = getServerId();
           GM_setValue('tradeRoutes_' + serverID, JSON2.stringify(t.tradeRoutes));
       },
     readTradeRoutes: function(){
           var t = Tabs.TranspAuto;
           var serverID = getServerId();
           s = GM_getValue('tradeRoutes_' + serverID);
           if (s != null) {
               route = JSON2.parse(s);
               for (k in route)
                   t.tradeRoutes[k] = route[k];
           }
       },
   	saveTraderState: function(){
   		var t = Tabs.TranspAuto;
           var serverID = getServerId();
           GM_setValue('traderState_' + serverID, JSON2.stringify(t.traderState));
       },
       readTraderState: function(){
           var t = Tabs.TranspAuto;
           var serverID = getServerId();
           s = GM_getValue('traderState_' + serverID);
           if (s != null) {
               state = JSON2.parse(s);
               for (k in state)
                   t.traderState[k] = state[k];
           }
       },
       toggleTraderState: function(obj){
   	   var t = Tabs.TranspAuto;
   	   obj = ById('pbTraderState');
           if (t.traderState.running == true) {
               t.traderState.running = false;
               if (obj)  obj.value = "Transport = OFF";
   	       updatebotbutton('Transp - OFF', 'pbtrantab');
   	       clearTimeout(t.checkdotradetimeout);
   	       t.count = 0;
   	       Options.lasttransport = 0;
	       saveOptions();
           }
           else {
               t.traderState.running = true;
               if (obj) obj.value = "Transport = ON";
   		updatebotbutton('Transp - ON', 'pbtrantab');
   			t.e_tradeRoutes();
           }
       },
   	
   	checkdoTrades: function(){
   	var t = Tabs.TranspAuto;
   	if(t.tradeRoutes.length==0) return;
   	t.doTrades(t.count);
   	t.count++;
   	if(t.count < t.tradeRoutes.length){
   			  t.checkdotradetimeout = setTimeout(function() { t.checkdoTrades();}, 5000);
   			} else {
   			  var now = new Date().getTime()/1000.0;
   			  now = now.toFixed(0);
   			  Options.lasttransport = now;
   			  saveOptions();	
   			  t.count = 0;
   			}
   	},
       
     doTrades: function(count){
       var t = Tabs.TranspAuto;
   
      	if(t.tradeRoutes.length==0) return;
      	if(!t.tradeRoutes[count]["route_state"]) return;
      	
      	var city = t.tradeRoutes[count]["city"];
      	if(!Cities.byID[city]) return;
	   		
	var xcoord = t.tradeRoutes[count]["target_x"];
       	var ycoord = t.tradeRoutes[count]["target_y"];
   	var cityID = 'city' + city;
   	for (var zz=0; zz< Seed.cities.length;zz++) {
	   if (parseInt(Seed.cities[zz][0]) == city) 
	      var cityname = Seed.cities[zz][1];
	}                     
   		
      	var rallypointlevel = t.getRallypoint(cityID);
	if(rallypointlevel == 12) rallypointlevel = 11;
        var slots = 0;
	for (var k in Seed.queue_atkp[cityID]){   
	         	         march = Seed.queue_atkp[cityID][k];
	         	         if (typeof (march) == 'object'){
	         	           slots++;
	         	         }
	}
	if(slots >= rallypointlevel){
	      		actionLog("Transport","Transport de "+cityname+" vers " + xcoord + "," + ycoord + " <font color=red>Point de ralliement complet !</font>");
	      		return;
        }
      	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
   		params.gold =0;
   		params.r1 =0;
   		params.r2 =0;
   		params.r3 =0;
   		params.r4 =0 ;
   		params.r5 =0 ;
   		params.kid = 0;
   		
   		var carry_amount= 0;
   		var wagons_needed=0;
   		var citymax = 0;
   		
   		

       	var trade_Food = t.tradeRoutes[count]["trade_Food"];
       	var trade_Wood = t.tradeRoutes[count]["trade_Wood"];
       	var trade_Stone = t.tradeRoutes[count]["trade_Stone"];
       	var trade_Ore = t.tradeRoutes[count]["trade_Ore"];
   	var trade_Astone = t.tradeRoutes[count]["trade_Astone"];
       	var trade_Gold = t.tradeRoutes[count]["trade_Gold"];
       	var target_Food = t.tradeRoutes[count]["target_Food"];
       	var target_Wood = t.tradeRoutes[count]["target_Wood"];
       	var target_Stone = t.tradeRoutes[count]["target_Stone"];
       	var target_Ore = t.tradeRoutes[count]["target_Ore"];
   		var target_Astone = t.tradeRoutes[count]["target_Astone"];
       	var target_Gold = t.tradeRoutes[count]["target_Gold"];
       	var ship_Food = t.tradeRoutes[count]["ship_Food"];
       	var ship_Wood = t.tradeRoutes[count]["ship_Wood"];
       	var ship_Stone = t.tradeRoutes[count]["ship_Stone"];
       	var ship_Ore = t.tradeRoutes[count]["ship_Ore"];
   		var ship_Astone = t.tradeRoutes[count]["ship_Astone"];
       	var ship_Gold = t.tradeRoutes[count]["ship_Gold"];
       	var citymax_Food = parseIntNan(Seed.resources[cityID]['rec1'][0] / 3600);
       	var citymax_Wood = parseIntNan(Seed.resources[cityID]['rec2'][0] / 3600);
       	var citymax_Stone = parseIntNan(Seed.resources[cityID]['rec3'][0] / 3600);
       	var citymax_Ore = parseIntNan(Seed.resources[cityID]['rec4'][0] / 3600);
   		var citymax_Astone = parseIntNan(Seed.resources[cityID]['rec5'][0]);
       	var citymax_Gold = parseIntNan(Seed.citystats[cityID]['gold']);
       	var carry_Food = parseIntNan(citymax_Food - target_Food);
       	var carry_Wood = parseIntNan(citymax_Wood - target_Wood);
       	var carry_Stone = parseIntNan(citymax_Stone - target_Stone);
       	var carry_Ore = parseIntNan(citymax_Ore - target_Ore);
   		var carry_Astone = parseIntNan(citymax_Astone - target_Astone);
       	var carry_Gold = 0;
       	if (carry_Food < 0 || ship_Food==false) carry_Food = 0;
       	if (carry_Wood < 0 || ship_Wood==false) carry_Wood = 0;
       	if (carry_Stone < 0 || ship_Stone==false) carry_Stone = 0;
       	if (carry_Ore < 0 || ship_Ore==false) carry_Ore = 0;
   		if (carry_Astone < 0 || ship_Astone==false) carry_Astone = 0;
       	if (trade_Food > 0 && (carry_Food > trade_Food)) carry_Food = parseIntNan(trade_Food);
       	if (trade_Wood > 0 && (carry_Wood > trade_Wood)) carry_Wood = parseIntNan(trade_Wood);
       	if (trade_Stone > 0 && (carry_Stone > trade_Stone)) carry_Stone = parseIntNan(trade_Stone);
       	if (trade_Ore > 0 && (carry_Ore > trade_Ore)) carry_Ore = parseIntNan(trade_Ore);
   	if (trade_Astone > 0 && (carry_Astone > trade_Astone)) carry_Astone = parseIntNan(trade_Astone);
   		carry_Astone *= 5;         
         if (t.tradeRoutes[count]['TroopType'] == undefined) var wagons = parseInt(Seed.units[cityID]['unt'+ 9]); 
         else var wagons =  parseInt(Seed.units[cityID][t.tradeRoutes[count]['TroopType']]);
         var rallypointlevel = t.getRallypoint(cityID);	
   		  if (rallypointlevel == 11) rallypointlevel = 15;
   		  if (rallypointlevel == 12) rallypointlevel = 20;
       	if (parseInt(wagons) > parseInt(rallypointlevel*10000)){ wagons = (rallypointlevel*10000); }   	
         if (t.tradeRoutes[count]['TroopType'] == undefined) var unit = 'unt9';
         else var unit = t.tradeRoutes[count]['TroopType'];
         var Troops = parseInt(Seed.units[cityID][unit]);
   	  if(parseInt(Troops)>parseInt(wagons)) Troops = wagons;
         var featherweight = parseInt(Seed.tech.tch10);
       	var Load = parseInt(unsafeWindow.unitstats[unit]['5'])
         var maxloadperwagon = (featherweight * ((Load/100)*10)) + Load;
   		  var maxload = (maxloadperwagon * Troops);
   		  if(wagons <= 0) {return; }
   		  var shift_Food = parseIntNan(maxload / 9);
   		  var shift_Wood = parseIntNan(maxload / 9);
   		  var shift_Stone = parseIntNan(maxload / 9);
   		  var shift_Ore = parseIntNan(maxload / 9);
   		  var shift_Astone = parseIntNan(maxload / 9 * 5); 	
   		  if ((maxload - carry_Food - carry_Wood - carry_Stone - carry_Ore - carry_Astone) < 0){
   			 var shift_num=0;
   			 var shift_spare=0;
   			if (carry_Food < shift_Food) {
   				shift_spare += (shift_Food - carry_Food);
   				shift_Food = carry_Food;
   			}
   			if (carry_Wood < shift_Wood) {
   				shift_spare += (shift_Wood - carry_Wood);
   				shift_Wood = carry_Wood;	
   			}
   			if (carry_Stone < shift_Stone) {
   				shift_spare += (shift_Stone - carry_Stone);
   				shift_Stone = carry_Stone;
   			}
   			if (carry_Ore < shift_Ore) {
   				shift_spare += (shift_Ore - carry_Ore);
   				shift_Ore = carry_Ore;
   			}
               if (carry_Astone < shift_Astone) {
   				shift_spare += (shift_Astone - carry_Astone);
   				shift_Astone = carry_Astone;
   			}						
   			 
   		  while (shift_spare >1) {
   				 if (carry_Food < (shift_Food + shift_spare)){
   				    shift_spare = shift_spare - carry_Food;;
   				    shift_Food = carry_Food;
   				 }
   				 else{
   				  shift_Food = (shift_Food + shift_spare);
   				  shift_spare = shift_spare- shift_spare;
   				}
   				 if (carry_Wood < (shift_Wood + shift_spare)){
   				    shift_spare = shift_spare - carry_Wood;;
   				    shift_Wood = carry_Wood;
   				 }
   				 else{
   				  shift_Wood = shift_Wood + shift_spare;
   				  shift_spare = shift_spare- shift_spare;
   				}
           		if (carry_Stone < (shift_Stone + shift_spare)){
   				    shift_spare = shift_spare - carry_Stone;
   				    shift_Stone = carry_Stone;
   				 }
   				 else{
   				  shift_Stone = shift_Stone + shift_spare;
   				  shift_spare = shift_spare- shift_spare;
   				}
   				 if (carry_Ore < (shift_Ore + shift_spare)){
   				    shift_spare = shift_spare - carry_Ore;
   				    shift_Ore = carry_Ore;
   				 }
   				 else{
   				  shift_Ore = shift_Ore + shift_spare;
   				  shift_spare = shift_spare- shift_spare;
   				}
   				if (carry_Astone < (shift_Astone + shift_spare)){
   				    shift_spare = shift_spare - carry_Astone;
   				    shift_Astone = carry_Astone;
   				 }
   				 else{
   				  shift_Astone = shift_Astone + shift_spare;
   				  shift_spare = shift_spare- shift_spare;
   				}
   			 }
   
   		carry_Food = shift_Food;
   		carry_Wood = shift_Wood;
   		carry_Stone = shift_Stone;
   		carry_Ore = shift_Ore;
   		carry_Astone = shift_Astone;
   		}
   		
   		if (maxload > (carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone) && ship_Gold==true) {
   		    if ((maxload-(carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone)) > (citymax_Gold - target_Gold)){
   		    	  carry_Gold = (citymax_Gold - target_Gold);
   		    	  if (carry_Gold < 0 ) carry_Gold = 0;
   		   	}
   		    else carry_Gold = (maxload-(carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone));
   		    if (trade_Gold > 0 && (carry_Gold > trade_Gold)) carry_Gold = parseInt(trade_Gold);
   		}
   		
   		wagons_needed = ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) / maxloadperwagon);
   		wagons_needed = wagons_needed.toFixed(0);	
   		if (wagons_needed < ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) / maxloadperwagon)) wagons_needed++;	
   		if ( wagons_needed < Options.minwagons ) { return; }
           
   		params.cid= city;
   		params.type = "1";
   		params.xcoord = xcoord;
   		params.ycoord = ycoord;
   		params.r1 = carry_Food;
   		params.r2 = carry_Wood;
   		params.r3 = carry_Stone;
   		params.r4 = carry_Ore;
   		params.r5 = parseInt(carry_Astone/5);
   		params.gold = carry_Gold;
   		
   		switch (unit){
         case 'unt1': params.u1 = wagons_needed;break;
         case 'unt2': params.u2 = wagons_needed;break;
         case 'unt3': params.u3 = wagons_needed;break;
         case 'unt4': params.u4 = wagons_needed;break;
         case 'unt5': params.u5 = wagons_needed;break;
         case 'unt6': params.u6 = wagons_needed;break;
         case 'unt7': params.u7 = wagons_needed;break;
         case 'unt8': params.u8 = wagons_needed;break;
         case 'unt9': params.u9 = wagons_needed;break;
         case 'unt10': params.u10 = wagons_needed;break;
         case 'unt11': params.u11 = wagons_needed;break;
         case 'unt12': params.u12 = wagons_needed;break;
       }
      if ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) > 0) {
    
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                     method: "post",
                     parameters: params,
                     loading: true,
                     onSuccess: function (transport) {
                     var rslt = eval("(" + transport.responseText + ")");
                     if (rslt.ok) {
                     var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                     var ut = unsafeWindow.unixtime();
                     var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                     for(i = 0; i <= unitsarr.length; i++){
                     	if(params["u"+i]){
                     	unitsarr[i] = params["u"+i];
                     	}
                     }
                     var resources=new Array();
                     resources[0] = params.gold;
                     for(i=1; i<=5; i++){
                     	resources[i] = params["r"+i];
                     }
                     var currentcityid = city;
                     unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                     unsafeWindow.update_seed(rslt.updateSeed)
                     if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                      actionLog("Transport","Depuis: " + cityname + " Vers : " + xcoord + ',' + ycoord + "  -> "+ unsafeWindow.unitcost[unit][0] +": " + wagons_needed);
                     } else {
			actionLog("Transport","Depuis: " + cityname + " Vers : " + xcoord + ',' + ycoord + "<br><font color=red>" + transport.responseText + "</font>");
                     }
                     },
                     onFailure: function (transport) {actionLog("Transport","Depuis: " + cityname + " Vers : " + xcoord + ',' + ycoord + "<br><font color=red>" + transport.responseText + "</font>");}
             });
           }
   	},
   	
   ManualTransport: function(){
       var t = Tabs.TranspAuto;
 
    if (document.getElementById ('ptcityX').value == "" || document.getElementById ('ptcityY').value == "") return;
    if ( t.TroopsNeeded > t.Troops) return;
       
      	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
       var unitType = ById('TransportTroop').value;
      // var LoadUnit = (parseInt(Seed.tech.tch10) * ((parseInt(unsafeWindow.unitstats[unitType]['5'])/100)*10)) + parseInt(unsafeWindow.unitstats[unitType]['5']);
        	     var untid=ById('TransportTroop').value;
       	     var techLoadBoost=parseInt(Seed.tech.tch10)*0.1;
       	     var loadEffectBoost=0;
       	     if(Seed.playerEffects.loadExpire>uW.unixtime()){loadEffectBoost=0.25}
       	     var loadBoostBase=(uW.cm.ThroneController.effectBonus(6)*0.01)+loadEffectBoost+techLoadBoost;
       	     var loadBoost=loadBoostBase;
       	     if(uW.cm.unitFrontendType[untid]=="siege"){
       	      loadBoost+=(uW.cm.ThroneController.effectBonus(59)*0.01)
       	     }else{
       	      if(uW.cm.unitFrontendType[untid]=="horsed"){
       	       loadBoost+=(uW.cm.ThroneController.effectBonus(48)*0.01)
       	      }
          	 }
       	  var LoadUnit=parseInt(parseInt(uW.unitstats[untid][5])*(1+loadBoost));
       var MaxLoad =  parseInt(Seed.units['city' + t.tcp.city.id][unitType]) * LoadUnit;
       document.getElementById ('errorSpace').innerHTML = '';
         	
   	params.kid = 0;
        params.cid=  t.tcp.city.id;
   	params.type = "1";
   	params.xcoord = parseInt(document.getElementById ('ptcityX').value);
   	params.ycoord = parseInt(document.getElementById ('ptcityY').value);
   	params.r1 = parseInt(document.getElementById ('pbtradeamountFood').value);
   	params.r2 = parseInt(document.getElementById ('pbtradeamountWood').value);
   	params.r3 = parseInt(document.getElementById ('pbtradeamountStone').value);
   	params.r4 = parseInt(document.getElementById ('pbtradeamountOre').value);
   	params.r5 = parseInt(document.getElementById ('pbtradeamountAstone').value);
   	params.gold = parseInt(document.getElementById ('pbtradeamountGold').value);
   		
       switch (unitType){
         case 'unt1': params.u1 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt2': params.u2 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt3': params.u3 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt4': params.u4 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt5': params.u5 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt6': params.u6 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt7': params.u7 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt8': params.u8 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt9': params.u9 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt10': params.u10 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt11': params.u11 = parseInt(document.getElementById ('TroopsToSend').value);break;
         case 'unt12': params.u12 = parseInt(document.getElementById ('TroopsToSend').value);break;
       }
   
       if ((params.r1 + params.r2 + params.r3 + params.r4 + params.r5 + params.gold) > 0) {   
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                     method: "post",
                     parameters: params,
                     loading: true,
                     onSuccess: function (transport) {
                     var rslt = eval("(" + transport.responseText + ")");
                     if (rslt.ok) {                  
   		                  var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
   		                  var ut = unixTime();
   		                  var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
   		                  for(i = 0; i <= unitsarr.length; i++){
   		                  	if(params["u"+i]){
   		                  	unitsarr[i] = params["u"+i];
   		                  	}
   		                  }
   		                  var resources=new Array();
   		                  resources[0] = params.gold;
   		                  for(i=1; i<=5; i++){
   		                  	resources[i] = params["r"+i];
   		                  }
   		                  var currentcityid = t.tcp.city.id;
   		                  unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
   		                  if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
   		                  document.getElementById ('errorSpace').innerHTML = 'Envoy&eacute;: ' + addCommas(params.r1+params.r2+params.r3+params.r4+params.r5+params.gold) + ' Ressources avec ' + addCommas(parseInt(document.getElementById ('TroopsToSend').value)) + ' ' + unsafeWindow.unitcost[unitType][0];
   		                  document.getElementById ('pbtradeamountFood').value = 0;
   		                  document.getElementById ('pbtradeamountWood').value = 0;
   		                  document.getElementById ('pbtradeamountStone').value = 0;
   		                  document.getElementById ('pbtradeamountOre').value = 0;
   						  document.getElementById ('pbtradeamountAstone').value = 0;
   		                  document.getElementById ('pbtradeamountGold').value = 0;
   		                  document.getElementById ('TroopsToSend').value = 0;
                     } else {
   		                  var errorcode =  'err_' + rslt.error_code;
   		                  if (rlst.msg == undefined)document.getElementById ('errorSpace').innerHTML = '<HR><FONT COLOR=red>Error: ' + unsafeWindow.g_js_strings.errorcode[errorcode] +'</font>';
   		                  else document.getElementById ('errorSpace').innerHTML = '<HR><FONT COLOR=red>Erreur : ' + rslt.msg +'</font>'; 
                     }
                     },
                     onFailure: function () {}
             });
           }
   	},
	
  onUnload: function(){
     var t = Tabs.TranspAuto;
     if (!ResetAll) t.saveTradeRoutes();
     if (!ResetAll) t.saveTraderState();
     if (!ResetAll) t.saveReapproState();
  },
  showManuel : function() {
   var t = Tabs.TranspAuto
   var rownum = 0;

   var ModelCity = {};
   
   function _row (name, row, noTotal){
      if (rownum++ % 2)
        style = '';
      else
        style = ' style = "background: #e8e8e8"';
      var tot = 0;
      var m = [];
      m.push ('<TR style="background: #fff" align=right');
      m.push (style);
      m.push ('><TD');
      m.push (style);
      m.push ('><B>');
      m.push (name);
      m.push ('</td>');
      if (noTotal){
        m.push ('<TD');
        m.push (style);
        m.push ('>&nbsp;</td>');
      } else {
        for (i=0; i<row.length; i++)
          tot += row[i];
        m.push ('<TD style="background: #ffc">');
        m.push (addCommas(tot));
        m.push ('</td>');
      }
      for (i=0; i<row.length; i++){
        m.push ('<TD');
        m.push (style);
        m.push ('>');
        m.push (addCommas(row[i]));
        m.push ('</td>');
      }
      m.push ('</tr>');
      return m.join('');
    }
    dt = new Date ();
    dt.setTime (Seed.player.datejoinUnixTime * 1000);
    if (t.state == null) {  
      m = "<DIV class=boStat>Transporter des marchandises d'une ville a une autre</div>";
      m +="<div id='statpourTr'></div>";
      m += "<TABLE width=100% class=ptTab border=0>\
       <tr align=center><td colspan=2><HR></td></tr>\
       <tr align=center valign=top><td colspan=1 width=50%><b><u>Source</b></u><br><span id=srcptspeedcity></span></td>\
       <td colspan=1 width=50%  rowspan=2><b><u>Destination</b></u><br><span id=desptspeedcity></span><br>\
       Ou des coordonn&eacute;es <br>X: <input type=text size=4 id=typetrpx value=0>&nbsp;Y: <input type=text size=4 id=typetrpy value=0><br><a href='javascript:void(0);' id='chargelistelieux'>Membres</a> : <select id='BOlisteFavori'></select><br><br><INPUT id='ptttButTransport' type=submit value='Transporter' style='font-weight:bold'>\
       </td></tr>\
       <tr align=center><td colspan=1>Unit&eacute : <select id=typetrp><option selected value='1'>Unite de ravitaillement</option><option selected value='9'>Wagon</option><option value='7'>Cavalerie</option><option value='8'>Cavalerie lourde</option></select>\
       <br>Quantit&eacute; : <input type=text size=6 value='1000' id='Choixnbwagon'><input type=button id='trswagmax' value='Max'\><br><i>(la quantit&eacute de ressource est le maximun des unit&eacute;s choisies)</i>\
       <br><b>Ressource :</b><input type=radio id='ChoixRess0' name='ChoixRess' value='gold' style='visibility:hidden'><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_30.png onclick=document.getElementById('ChoixRess0').checked=true;BOestimeres(); height=20>\
       <input type=radio id='ChoixRess1' name='ChoixRess' value='rec1' style='visibility:hidden'><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png onclick=document.getElementById('ChoixRess1').checked=true;BOestimeres(); height=20>\
       <input type=radio id='ChoixRess2' name='ChoixRess' value='rec2' style='visibility:hidden'><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png onclick=document.getElementById('ChoixRess2').checked=true;BOestimeres(); height=20>\
       <input type=radio id='ChoixRess3' name='ChoixRess' value='rec3' style='visibility:hidden'><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png onclick=document.getElementById('ChoixRess3').checked=true;BOestimeres(); height=20>\
       <input type=radio id='ChoixRess4' name='ChoixRess' value='rec4' style='visibility:hidden'><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png onclick=document.getElementById('ChoixRess4').checked=true;BOestimeres(); height=20>\
       <input type=radio id='ChoixRess5' name='ChoixRess' value='rec5' style='visibility:hidden'><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png onclick=document.getElementById('ChoixRess5').checked=true;BOestimeres(); height=20>\
       </td></tr>\
       <tr><td colspan=2>Estimation des ressources transport&eacute;es : <span id=BOEstimationR></td></tr>\
       </table>\
       <TABLE align=center width=100% class=ptTab><TR><TD><div id=ptTranportStatus style='text-align:center;overflow-y:auto; max-height:78px; height: 78px;'></div></td></tr></table>";
    t.TransportDiv.innerHTML = m; 
    t.destinationCityx = document.getElementById ('typetrpx');
    t.destinationCityy = document.getElementById ('typetrpy');
    
    t.destinationCityx.addEventListener ('change', t.estimerRes, false);
    t.destinationCityy.addEventListener ('change', t.estimerRes, false);
    document.getElementById ('ChoixRess0').addEventListener ('click', t.estimerRes, false);
    document.getElementById ('ChoixRess1').addEventListener ('click', t.estimerRes, false);
    document.getElementById ('ChoixRess2').addEventListener ('click', t.estimerRes, false);
    document.getElementById ('ChoixRess3').addEventListener ('click', t.estimerRes, false);
    document.getElementById ('ChoixRess4').addEventListener ('click', t.estimerRes, false);
    document.getElementById ('ChoixRess5').addEventListener ('click', t.estimerRes, false);     
    t.listeFavoris = document.getElementById ('BOlisteFavori');
    t.estimationRes = document.getElementById ('BOEstimationR');
    t.chargelistelieux = document.getElementById ('chargelistelieux');
    t.chargelistelieux.addEventListener ('click', t.chercherFavoris, false);
    t.listeFavoris.addEventListener ('change', t.SelectFavoris, false);   
    var dcp1 = new CdispCityPicker ('ptspeed1', ById('desptspeedcity'), false, t.clickCityDestinationSelect, 1);
    t.TTbutTransport = document.getElementById ('ptttButTransport');
    t.TTbutTransport.addEventListener ('click', t.clickTransportDo, false);
    t.divTranportStatus = document.getElementById ('ptTranportStatus');
    t.statpourTr = document.getElementById ('statpourTr');
    t.typetrp = document.getElementById ('typetrp');
    t.typetrp.addEventListener ('click', t.estimerRes, false); 
    t.trswagmax = document.getElementById ('trswagmax');
    t.trswagmax.addEventListener ('click', t.clickUniteMax, false);
    t.Choixnbwagon  = document.getElementById ('Choixnbwagon');
    t.Choixnbwagon.addEventListener ('keyup', t.verifierWagons, false);
    var dcp0 = new CdispCityPicker ('ptspeed0', ById('srcptspeedcity'), false, t.clickCitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
    t.state = 1;
   }
   if (t.state == 1) {
    if (document.getElementById ('maparea_map').style.display!="none") {
       t.destinationCityx.value = document.getElementById ('mapXCoor').value;
       t.destinationCityy.value = document.getElementById ('mapYCoor').value;
       t.destinationCityx.style.backgroundColor="#FF9999";
       t.destinationCityy.style.backgroundColor="#FF9999";
       setTimeout(function() {
             t.destinationCityx.style.backgroundColor="#fff";
       t.destinationCityy.style.backgroundColor="#fff";
       }, 3000);
                    
    }
    t.state = 2;
   }
   rows=[];
   rows[0]=[];
   m = "<TABLE class=ptTabLined cellspacing=0><TR valign=top align=right><TD width=65></td><TD width=88 style='background: #ffc'><B>TOTAL</b></td>";
      for(i=0; i<Cities.numCities; i++)
         m += '<TD width=81><B>'+ Cities.cities[i].name.substring(0,10) +'</b></td>';
      for(i=0; i<Cities.numCities; i++) {
        cityID = 'city'+ Cities.cities[i].id;
        rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
      }
      for (r=1; r<6; r++){
        rows[r] = [];
        for(i=0; i<Cities.numCities; i++) {
          cityID = 'city'+ Cities.cities[i].id;
           if (r==5)
	    rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
	            else
           rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
        }
      }
      m += _row ('<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_30.png>', rows[0]);
      m += _row ('<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png>', rows[1]);
      m += _row ('<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png>', rows[2]);
      m += _row ('<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png>', rows[3]);
      m += _row ('<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png>', rows[4]);
      m += _row ('<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png>', rows[5]);
      m += '<TR><TD><font size=1><BR></td></tr>';
      row = [];
      var totalbouffe = 0;
      for(i=0; i<Cities.numCities; i++) {
	var rp = getResourceProduction (Cities.cities[i].id);
	var usage = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
	row[i] = rp[1] - usage;
      }
      m += _row ('Prod', row, false,  0);
      for(i=0; i<Cities.numCities; i++) {
                    if (row[i] >= 0)
                      row[i] = '----';
                    else {
                      var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-row[i]) * 3600;
                      if (timeLeft > 86313600)
                        row[i] = '----';
                      else {
                        if (Options.enableFoodWarn && timeLeft<(Options.foodWarnHours*3600))
                          row[i] = '<SPAN class=whiteOnRed>'+ timestrShort(timeLeft) +'</span>';
                        else
                          row[i] = timestrShort(timeLeft);
                      }
                    }
      }    
      m += _row ('Aut.', row, true, 0);
      m += '<TR><TD><font size=1><BR></td></tr>';
      for (r=1; r<13; r++){
        rows[r] = [];
        for(i=0; i<Cities.numCities; i++) {
          cityID = 'city'+ Cities.cities[i].id;
          rows[r][i] = parseInt(Seed.units[cityID]['unt'+r]);
        }
      }
      m += _row ('<img height=20 title="'+unsafeWindow.unitcost['unt1'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_1_30_s34.jpg>', rows[1]);
      m += _row ('<img height=20 title="'+unsafeWindow.unitcost['unt7'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_7_30_s34.jpg>', rows[7]);
      m += _row ('<img height=20 title="'+unsafeWindow.unitcost['unt8'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_8_30_s34.jpg>', rows[8]);
      m += _row ('<img height=20 title="'+unsafeWindow.unitcost['unt9'][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_30_s34.jpg>', rows[9]);
          row = [];
    for(i=0; i<Cities.numCities; i++) {
    	        var cityId = 'city'+ Cities.cities[i].id;
    	        var slots = 0;
    	        for (var k in Seed.queue_atkp[cityId]){   
    	         march = Seed.queue_atkp[cityId][k];
    	         if (typeof (march) == 'object'){
    	           slots++;
    	         }
    	        }
	var niveauPointRall=parseInt(getCityBuilding (Cities.cities[i].id, 12).maxLevel);
	if (niveauPointRall==12) niveauPointRall=11;
    	row[i] = '<SPAN><B>'+ slots +'/'+ niveauPointRall +'</b></span>';
     }
    m += _row ('PR', row, true, 0);   m += "</table>";
     t.statpourTr.innerHTML = m;
     clearTimeout (t.displayTimer);
     t.displayTimer = setTimeout (t.showManuel, 4000);
  },
  
  SelectFavoris:function() {
   var t = Tabs.TranspAuto;
   if (t.listeFavoris.value!='') {
    var valeur=t.listeFavoris.value;
    var x=valeur.substr(0, valeur.lastIndexOf(','));
    var y=valeur.substr(valeur.lastIndexOf(',')+1, valeur.length);
    t.destinationCityx.value = x;
    t.destinationCityy.value = y;
   }
   t.estimerRes();
  },
  
  chercherFavoris: function() {
   var t = Tabs.TranspAuto;
   var myA = getMyAlliance ();
   if (myA[0]!=0) {
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.perPage = 100;
      params.allianceId = myA[0];
          new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
	        method: "post",
	        parameters: params,
	        onSuccess: function (rslt) {
	          if (rslt.ok){
	           var z=0;
	           var m="";
	           for (var i=0; i<rslt.results.length; i++){
     		      p = rslt.results[i];
		      if (p.userId != 0){
		       for (var c=0; c<p.cities.length; c++){
		         if (Seed.player.name!=p.displayName) {
		          m += "<option value='" + p.cities[c].xCoord + ","+ p.cities[c].yCoord+"'>" + p.displayName + " - "+unsafeWindow.g_js_strings.commonstr.city+" " + (c+1) + " - " + p.cities[c].xCoord + "," + p.cities[c].yCoord+"</option>";
		         }
		       }  	       
		      } 
      	            } 
      	            t.listeFavoris.innerHTML="<option value=''>Selectionner...</option>"+m;
	          }
	        },
	        onFailure: function (rslt) {
	          t.listeFavoris.innerHTML="<option>Erreur</option>";
	        },
    	});
   } else {
     t.listeFavoris.innerHTML="<option>Pas d'alliance !</option>";
   }   
  },
  verifierWagons: function() {
   var t = Tabs.TranspAuto;
   var maxw=parseInt(rows[t.typetrp.value][t.sourceCity.idx]);
   var saisw=parseInt(t.Choixnbwagon.value);
   if (saisw > maxw) {
      t.Choixnbwagon.value=maxw;
      t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>La quantit&eacute; ne peut exc&eacute;der '+maxw+' !.</font>';
   }
   t.estimerRes();
  },
  estimerRes: function() {
   var t = Tabs.TranspAuto;
   var cityID = 'city'+ t.sourceCity.id,ic=0,resact=0,ic_ty="gold",ic_text="d'or";
   if (ById("ChoixRess1").checked) { ic_ty="rec1";ic=1;ic_text="de "+unsafeWindow.g_js_strings.commonstr.food; }
   if (ById("ChoixRess2").checked) { ic_ty="rec2";ic=2;ic_text="de bois"; }
   if (ById("ChoixRess3").checked) { ic_ty="rec3";ic=3;ic_text="de pierre"; }
   if (ById("ChoixRess4").checked) { ic_ty="rec4";ic=4;ic_text="de minerais"; }
   if (ById("ChoixRess5").checked) { ic_ty="rec5";ic=5;ic_text="de "+uW.g_js_strings.commonstr.aetherstone; }
   if (ById("ChoixRess0").checked) { ic_ty="gold";ic=0;ic_text="d'or"; } 
   var esti = 0;//parseInt(unsafeWindow.unitstats['unt'+t.typetrp.value][5] * t.Choixnbwagon.value * (1 + (0.10 * Seed.tech.tch10)));
   
   var total_units=t.Choixnbwagon.value;
   var untid=t.typetrp.value;
   var techLoadBoost=parseInt(Seed.tech.tch10)*0.1;
   var loadEffectBoost=0;
   if(Seed.playerEffects.loadExpire>uW.unixtime()){loadEffectBoost=0.25}
   var loadBoostBase=(uW.cm.ThroneController.effectBonus(6)*0.01)+loadEffectBoost+techLoadBoost;
   var loadBoost=loadBoostBase;
   if(uW.cm.unitFrontendType[untid]=="siege"){
    loadBoost+=(uW.cm.ThroneController.effectBonus(59)*0.01)
   }else{
    if(uW.cm.unitFrontendType[untid]=="horsed"){
     loadBoost+=(uW.cm.ThroneController.effectBonus(48)*0.01)
    }
   }
   esti=parseInt(total_units*parseInt(uW.unitstats["unt"+untid][5])*(1+loadBoost));

   if (ic==5) esti = parseInt(esti / 5);
   var x1 = parseInt(t.sourceCity.x);
   var x2 = parseInt(t.destinationCityx.value);
   var y1 = parseInt(t.sourceCity.y);
   var y2 = parseInt(t.destinationCityy.value);
   var dist = distance (x1, y1, x2, y2);
   var m = estETA(dist,ById('typetrp').value,t.sourceCity.id,1);
   var a="";
   switch(ic){
    case 0:a=unsafeWindow.g_js_strings.commonstr.gold;break;
    case 1:a=unsafeWindow.g_js_strings.commonstr.food;break;
    case 2:a=unsafeWindow.g_js_strings.commonstr.wood;break;
    case 3:a=unsafeWindow.g_js_strings.commonstr.stone;break;
    case 4:a=unsafeWindow.g_js_strings.commonstr.ore;break;
    case 5:a=unsafeWindow.g_js_strings.commonstr.aetherstone;break;
   }
   t.estimationRes.innerHTML = "<b>" + addCommas(esti) + " "+a+"</b>";
   t.estimationRes.innerHTML += "<br>Estimation temps de marche : <b>" + m.friendEtaStr + "</b>" ; 
   
     if (ic==5)
      resact = parseIntNan(Seed.resources[cityID][ic_ty][0]);
     else {
      if (ic==0)
       resact = parseIntNan(Seed.citystats[cityID].gold[0]);
      else
       resact = parseIntNan(Seed.resources[cityID][ic_ty][0] / 3600);
     } 

    if (resact < esti) {
 
     var untid=t.typetrp.value;
     		     var techLoadBoost=parseInt(Seed.tech.tch10)*0.1;
     		     var loadEffectBoost=0;
     		     if(Seed.playerEffects.loadExpire>uW.unixtime()){loadEffectBoost=0.25}
     		     var loadBoostBase=(uW.cm.ThroneController.effectBonus(6)*0.01)+loadEffectBoost+techLoadBoost;
     		     var loadBoost=loadBoostBase;
     		     if(uW.cm.unitFrontendType[untid]=="siege"){
     		      loadBoost+=(uW.cm.ThroneController.effectBonus(59)*0.01)
     		     }else{
     		      if(uW.cm.unitFrontendType[untid]=="horsed"){
     		       loadBoost+=(uW.cm.ThroneController.effectBonus(48)*0.01)
     		      }
     	   	 }
       	  var nbparunit=parseInt(parseInt(uW.unitstats["unt"+untid][5])*(1+loadBoost));
     
     
     
     if (ic==5) nbparunit=parseInt(nbparunit/5);
     
     
     var uniteness = Math.floor(resact / nbparunit);
     if (uniteness<1) uniteness=0;
     t.Choixnbwagon.value = uniteness;
     t.TTbutTransport.disabled = false;  
     t.estimerRes();
   }
  }, 
  clickUniteMax: function() {
    var t = Tabs.TranspAuto;
    var maxw=parseInt(rows[t.typetrp.value][t.sourceCity.idx]);
    var niveauPointRall=parseInt(getCityBuilding (t.sourceCity.id, 12).maxLevel); 
        var e=1;
      var f=unsafeWindow.unixtime();
      if(Seed.playerEffects.aurasExpire){
      if(Seed.playerEffects.aurasExpire>f){e=1.15}}
      if(Seed.playerEffects.auras2Expire){if(Seed.playerEffects.auras2Expire>f){e=1.3}}  
    var maxtroupe=parseInt(niveauPointRall*10000*e);
    if (niveauPointRall==11) maxtroupe=parseInt(150000*e);
    if (niveauPointRall==12) maxtroupe=parseInt(200000*e);
    var q=uW.cm.ThroneController.effectBonus(66);
    maxtroupe=Math.round(maxtroupe*(1+q/100));
    
    if (maxw>maxtroupe) maxw=maxtroupe;
    t.Choixnbwagon.value=maxw;
    t.estimerRes();
  },
  clickTransportDo: function() { 
   var t = Tabs.TranspAuto;
   var SourceId = t.sourceCity.id;
   var DestinationId = t.destinationCity.id;
   if (!ById("ChoixRess0").checked && !ById("ChoixRess1").checked && !ById("ChoixRess2").checked && !ById("ChoixRess3").checked && !ById("ChoixRess4").checked && !ById("ChoixRess5").checked) {
       t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>Merci de cocher un type de ressource !</font>';
      return;
   }
   if (t.sourceCity.x==t.destinationCityx.value && t.sourceCity.y==t.destinationCityy.value) {
      t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>Impossible sur les m&ecirc; mes villes !.</font>';
     return;
   }
   if (parseInt(t.Choixnbwagon.value)=="0") {
   t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>Impossible de transporter avec 0 unit&eacute;e... pfff !.</font>';
     return;
   }
   var x=t.destinationCityx.value;
   var y=t.destinationCityy.value;
   if (x == 0 && y == 0) {
      t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>Impossible de transporter sur la destination 0,0 !.</font>';
     return;
   }
   t.TTbutTransport.disabled=true; 
   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
   params.kid = 0;
   params.cid= t.sourceCity.id;
   params.type = "1";
   params.xcoord = x;
   params.ycoord = y;
   params.r1 = 0;
   params.r2 = 0; 
   params.r3 = 0; 
   params.r4 = 0; 
   params.r5 = 0; 
   params.gold = 0; 
   params.u9 = 0;
   var untid=t.typetrp.value
   var techLoadBoost=parseInt(Seed.tech.tch10)*0.1;
   var loadEffectBoost=0;
    if(Seed.playerEffects.loadExpire>uW.unixtime()){loadEffectBoost=0.25}
   		     var loadBoostBase=(uW.cm.ThroneController.effectBonus(6)*0.01)+loadEffectBoost+techLoadBoost;
   		     var loadBoost=loadBoostBase;
   		     if(uW.cm.unitFrontendType[untid]=="siege"){
   		      loadBoost+=(uW.cm.ThroneController.effectBonus(59)*0.01)
   		     }else{
   		      if(uW.cm.unitFrontendType[untid]=="horsed"){
   		       loadBoost+=(uW.cm.ThroneController.effectBonus(48)*0.01)
   		      }
   }
   var esti=parseInt(t.Choixnbwagon.value * parseInt(uW.unitstats["unt"+untid][5])*(1+loadBoost));
   if (ById("ChoixRess5").checked) { 
    esti = parseInt(esti / 5);
   }
   if (ById("ChoixRess0").checked) { params.gold = esti; }
   if (ById("ChoixRess1").checked) { params.r1 = esti; }
   if (ById("ChoixRess2").checked) { params.r2 = esti; }
   if (ById("ChoixRess3").checked) { params.r3 = esti; }
   if (ById("ChoixRess4").checked) { params.r4 = esti; }
   if (ById("ChoixRess5").checked) { params.r5 = esti; }	
   if (t.typetrp.value==1)  params.u1 = t.Choixnbwagon.value;
   if (t.typetrp.value==9)  params.u9 = t.Choixnbwagon.value;
   if (t.typetrp.value==7)  params.u7 = t.Choixnbwagon.value;
   if (t.typetrp.value==8)  params.u8 = t.Choixnbwagon.value;

  t.divTranportStatus.innerHTML = "<i><b>"+uW.g_js_strings.commonstr.loadingddd+"....</b></i>";
   new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
              method: "post",
              parameters: params,
              loading: true,
              onSuccess: function (transport) {
                  var t = Tabs.TranspAuto;  
                  var rslt = transport;
                  if (rslt.ok) {
		   var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                   var ut = unsafeWindow.unixtime();
                   var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                   for(i = 0; i <= unitsarr.length; i++){
                   	if(params["u"+i]){
                  	unitsarr[i] = params["u"+i];
                  	}
                   }
                   var resources=new Array();
                   resources[0] = params.gold;
                   for(i=1; i<=4; i++){
                  	resources[i] = params["r"+i];
                   }
                   var currentcityid =  t.sourceCity.id;
                   unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                   unsafeWindow.update_seed(rslt.updateSeed)
                   if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                   t.divTranportStatus.innerHTML = "<font size='3px'><b>Transport effectu&eacute;.</b>";
                   t.TTbutTransport.disabled=false;
                  } else {
		    t.divTranportStatus.innerHTML ="<font color=red size='3px'><b>Erreur, merci de recommencer !<b></font>";
		     if (rslt.msg) {
		       t.divTranportStatus.innerHTML +="<br><font color=black size='2px'>" + rslt.msg +"</font>";
		       t.TTbutTransport.disabled=false;
         	     } else {
         	      t.divTranportStatus.innerHTML +="<br>Tentative dans 2 secondes !</font>";
         	      setTimeout(function() { t.clickTransportDo(); }, 2000);
         	     }
                  }
                  },
                  onFailure: function () {
                    var t = Tabs.TranspAuto;
                     t.divTranportStatus.innerHTML ="<font color=red size='3px'><b>Erreur, merci de recommencer !<b></font>";
                    t.TTbutTransport.disabled=false;
                  }
          });
  },
  clickCitySourceSelect : function (city){
    var t = Tabs.TranspAuto;
    t.sourceCity = city;
    t.TTbutTransport.disabled=false;
    var maxw=parseInt(rows[t.typetrp.value][t.sourceCity.idx]);
    var saisw=parseInt(t.Choixnbwagon.value);
    if (saisw > maxw)  t.Choixnbwagon.value=maxw;
    t.estimerRes();
   },
   clickCityDestinationSelect : function (city){
    var t = Tabs.TranspAuto;
    t.destinationCity = city;
    t.destinationCityx.value=t.destinationCity.x;
    t.destinationCityy.value=t.destinationCity.y;
    t.TTbutTransport.disabled=false;
    t.estimerRes();
   }, 
 
}

/*************** REASSIGNER **********/
var troops = {1:'SupplyTroops',
			  2:'Militiaman',
			  3:'Scout',
			  4:'Pikeman',
			  5:'Swordsman',
			  6:'Archer',
			  7:'Cavalry',
			  8:'HeavyCavalry',
			  9:'SupplyWagon',
			  10:'Ballista',
			  11:'BatteringRam',
			  12:'Catapult'}; 
Tabs.Reassign = {
  tabOrder: 7,
  tabLabel: uW.g_js_strings.commonstr.reassign,
 cont : null,
 displayTimer : null,
 state : null,
 curTabBut : null,
 curTabName : null,
 sourceCity : {},
 destinationCity : {},
 rows : [],
  timer: null,
  reassignState: [],
  lRE: [],
  reassignRoutes: [],
  rallypointlevel:null,
  count:0,
  check:false,
 show : function (){
 },
 hide : function (){
    var t = Tabs.Reassign;
    t.state = null;
    clearTimeout (t.displayTimer);
    clearTimeout (t.timer);
  },
  init : function (div){  
   var t = Tabs.Reassign;
   t.cont = div;
 
   t.reassignState = {                running: false,    };
   t.readReassignState();
   t.readReassignRoutes();
   t.e_reassignRoutes();
    		
   AddSubTabLink('Reassign', t.toggleReassignState, 'pbsigntab');
  if (t.reassignState.running == false) {
       	       updatebotbutton('Reassign - OFF', 'pbsigntab');
             } else {
       	      updatebotbutton('Reassign - ON', 'pbsigntab');
        }
  window.addEventListener('unload', t.onUnload, false);
  t.cont = div;
  t.cont.innerHTML = '<TABLE class=ptTab align=center><TR><TD><INPUT class=bopbSubtab ID=BoReeSubM type=submit value="Manuel"></td>\
             <TD><INPUT class=bopbSubtab ID=BoReeSubA type=submit  value="Automatique"></td></tr></table>\
         <DIV id="BoReeOutput" style="margin-top:5px; background-color:white; height:'+(Options.HauteurBoite-65)+'px;max-height:'+(Options.HauteurBoite-65)+'px;overflow-y:auto"></div>';
  t.ReassignDiv = ById('BoReeOutput'); 
  ById('BoReeSubA').addEventListener('click', e_butSubtab, false);
  ById('BoReeSubM').addEventListener('click', e_butSubtab, false);
  changeSubtab (ById('BoReeSubM'));  
  function e_butSubtab (evt){
          changeSubtab (evt.target);   
      }
  function changeSubtab (but){
          if (but == t.curTabBut)
            return;
          if (t.curTabBut){
            t.curTabBut.className='bopbSubtab'; 
            t.curTabBut.disabled=false;
          }
          t.curTabBut = but;
          but.className='bopbSubtab bopbSubtabSel'; 
          but.disabled=true;
          t.curTabName = but.id.substr(8);
          t.show2();
      }  
    
  },
   show2 : function (){
    var t = Tabs.Reassign ;
        t.state = null;
     clearTimeout (t.displayTimer);
     if (t.curTabName == 'M')
       t.showManuel();
     else
          t.showAuto();
     },
     
  showAuto: function() {   
      var t = Tabs.Reassign ; 
       clearTimeout (t.timer);
    if (t.state == null) {
  
      t.state = 1;  
      
           var m = '<DIV id=pbReMainDivF class=boStat>REASSIGNER AUTOMATIQUE - CONFIGURATION</div><TABLE id=pbtraderfunctions width=100% height=0% class=pbTab><TR align="center">';
      if (t.reassignState.running == false) {
          m += '<TD><INPUT id=pbReassignState type=submit value="Reassigne  = OFF"></td>';
	       updatebotbutton('Reassign - OFF', 'pbsigntab');
      } else {
          m += '<TD><INPUT id=pbReassignState type=submit value="Reassigne  = ON"></td>';
	      updatebotbutton('Reassign - ON', 'pbsigntab');
      }
      m += '<TD><INPUT id=pbReassShowRoutes type=submit value="Voir les Routes"></td>';
      m += '</tr></table></div>';
      m += '<DIV id=pbReassignDivD class=boStat>AJOUTER UNE ROUTE</div>';

      m += '<TABLE id=pbaddreasignroute width=95% height=0% class=pbTab><TR align="left">';
      m += '<TD width=20px>Depuis la ville :</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptassigncity></span></div></td></tr>';

      m += '<TR align="left">';
      m += '<TD width=20px>Vers la ville :</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptassigncityTo></span></div></td>';
	  
	    m += '<TR align="left">';
	    m += '<TD colspan=4>D&eacutelai entre chaque r&eacute;assignement : <INPUT id=pbreassigninterval type=text size=2 value="'+Options.reassigninterval+'"\> minutes</td></tr>';
	    m += '<TR><TD colspan=4><INPUT id=autofilloff type=checkbox unchecked=true\> Verouiller les valeurs de troupes</TR></TD></table>';
      m += '';
      m += '<TABLE id=pbaddreasignroute width=100% height=0% class=pbTab><TR align="center">';
      
      m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_1_50.jpg?6545"></td>';
      m += '<TD>'+unsafeWindow.unitcost['unt1'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt2'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt3'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt4'][0]+'</td></tr>'
      m += '<TR><TD><INPUT id=pbSupplyTroops type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetSupplyTroops disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbMilitiaman type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetMilitiaman disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbScout type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetScout disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbPikeman type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetPikeman disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
      
      m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_50.jpg?6545"></td>';
      m += '<TD>'+unsafeWindow.unitcost['unt5'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt6'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_7_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt7'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_8_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt8'][0]+'</td></tr>'
      m += '<TR><TD><INPUT id=pbSwordsman type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetSwordsman disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbArcher type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetArcher disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbCavalry type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetCavalry disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbHeavyCavalry type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetHeavyCavalry disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
      
      m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_50.jpg?6545"></td>';
      m += '<TD>'+unsafeWindow.unitcost['unt9'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://0cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt10'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt11'][0]+'</td>'
      m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_50.jpg?6545"></td>'
      m += '<TD>'+unsafeWindow.unitcost['unt12'][0]+'</td></tr>'
      m += '<TR><TD><INPUT id=pbSupplyWagon type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetSupplyWagon disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbBallista type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetBallista disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbBatteringRam type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetBatteringRam disabled=true type=text size=10 maxlength=10 value="0"\></td>';
      m += '<TD><INPUT id=pbCatapult type=checkbox unchecked=true\>';
      m += '<INPUT id=pbtargetCatapult disabled=true type=text size=10 maxlength=10 value="0"\></td></tr></table>';
      
      m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRouteReassign type=submit value="Add Route"></div>';
      
      t.ReassignDiv.innerHTML = m;
      
      t.tcp = new CdispCityPicker ('ptreassign', ById('ptassigncity'), true, null, 0);
	  t.tcpto = new CdispCityPicker ('ptreassignTo', ById('ptassigncityTo'), true);
	  for(var k in troops){
      ById('pbtarget'+troops[k]).value = parseInt(Seed.units['city' + t.tcp.city.id]['unt'+k]);
	  }

      ById('ptassigncity').addEventListener('click', function(){
		  if(ById('autofilloff').checked == false)
	    for(var k in troops)
        ById('pbtarget'+troops[k]).value = parseInt(Seed.units['city' + t.tcp.city.id]['unt'+k]);
      }, false);
      
      ById('pbReassignState').addEventListener('click', function(){
      	t.toggleReassignState(this);
      }, false);
      ById('pbSaveRouteReassign').addEventListener('click', function(){
      t.addReassignRoute();
      }, false);
      ById('pbReassShowRoutes').addEventListener('click', function(){
      t.showReassignRoutes();
      }, false);
      
      ById('pbreassigninterval').addEventListener('keyup', function(){
		if (isNaN(ById('pbreassigninterval').value)){ ById('pbreassigninterval').value=0 ;}
		Options.reassigninterval = ById('pbreassigninterval').value;
		saveOptions();
      }, false);
      
      ById('pbtargetSupplyTroops').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetSupplyTroops').value)) ById('pbtargetSupplyTroops').value=0 ;
      }, false);
      ById('pbtargetMilitiaman').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetMilitiaman').value)) ById('pbtargetMilitiaman').value=0 ;
      }, false);
      ById('pbtargetScout').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetScout').value)) ById('pbtargetScout').value=0 ;
      }, false);
      ById('pbtargetPikeman').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetPikeman').value)) ById('pbtargetPikeman').value=0 ;
      }, false);
      ById('pbtargetSwordsman').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetSwordsman').value)) ById('pbtargetSwordsman').value=0 ;
      }, false);
      ById('pbtargetArcher').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetArcher').value)) ById('pbtargetArcher').value=0 ;
      }, false);
      ById('pbtargetCavalry').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetCavalry').value)) ById('pbtargetCavalry').value=0 ;
      }, false);
      ById('pbtargetHeavyCavalry').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetHeavyCavalry').value)) ById('pbtargetHeavyCavalry').value=0 ;
      }, false);
      ById('pbtargetSupplyWagon').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetSupplyWagon').value)) ById('pbtargetSupplyWagon').value=0 ;
      }, false);
      ById('pbtargetBallista').addEventListener('keyup', function(){
          if (isNaN(ById('pbtargetBallista').value)) ById('pbtargetBallista').value=0 ;
      }, false);
     ById('pbtargetBatteringRam').addEventListener('keyup', function(){
         if (isNaN(ById('pbtargetBatteringRam').value)) ById('pbtargetBatteringRam').value=0 ;
     }, false);
     ById('pbtargetCatapult').addEventListener('keyup', function(){
         if (isNaN(ById('pbtargetCatapult').value)) ById('pbtargetCatapult').value=0 ;
     }, false);
     
      
      ById('pbSupplyTroops').addEventListener('click', function(){
          if (ById('pbSupplyTroops').checked==false) {
              ById('pbtargetSupplyTroops').disabled = true;
          }
          else {
            ById('pbtargetSupplyTroops').disabled = false;
          }
      },false);
      ById('pbMilitiaman').addEventListener('click', function(){
          if (ById('pbMilitiaman').checked==false) {
              ById('pbtargetMilitiaman').disabled = true;
          }
          else {
            ById('pbtargetMilitiaman').disabled = false;
          }
      },false);
      ById('pbScout').addEventListener('click', function(){
          if (ById('pbScout').checked==false) {
              ById('pbtargetScout').disabled = true;
          }
          else {
            ById('pbtargetScout').disabled = false;
          }
      },false);
      ById('pbPikeman').addEventListener('click', function(){
          if (ById('pbPikeman').checked==false) {
              ById('pbtargetPikeman').disabled = true;
          }
          else {
            ById('pbtargetPikeman').disabled = false;
          }
      },false);
      ById('pbSwordsman').addEventListener('click', function(){
          if (ById('pbSwordsman').checked==false) {
              ById('pbtargetSwordsman').disabled = true;
          }
          else {
            ById('pbtargetSwordsman').disabled = false;
          }
      },false);
      ById('pbArcher').addEventListener('click', function(){
          if (ById('pbArcher').checked==false) {
              ById('pbtargetArcher').disabled = true;
          }
          else {
            ById('pbtargetArcher').disabled = false;
          }
      },false);
      ById('pbCavalry').addEventListener('click', function(){
          if (ById('pbCavalry').checked==false) {
              ById('pbtargetCavalry').disabled = true;
          }
          else {
            ById('pbtargetCavalry').disabled = false;
          }
      },false);
      ById('pbHeavyCavalry').addEventListener('click', function(){
          if (ById('pbHeavyCavalry').checked==false) {
              ById('pbtargetHeavyCavalry').disabled = true;
          }
          else {
            ById('pbtargetHeavyCavalry').disabled = false;
          }
      },false);
      ById('pbSupplyWagon').addEventListener('click', function(){
          if (ById('pbSupplyWagon').checked==false) {
              ById('pbtargetSupplyWagon').disabled = true;
          }
          else {
            ById('pbtargetSupplyWagon').disabled = false;
          }
      },false);
      ById('pbBallista').addEventListener('click', function(){
          if (ById('pbBallista').checked==false) {
              ById('pbtargetBallista').disabled = true;
          }
          else {
            ById('pbtargetBallista').disabled = false;
          }
      },false);
      ById('pbBatteringRam').addEventListener('click', function(){
          if (ById('pbBatteringRam').checked==false) {
              ById('pbtargetBatteringRam').disabled = true;
          }
          else {
            ById('pbtargetBatteringRam').disabled = false;
          }
      },false);
      ById('pbCatapult').addEventListener('click', function(){
          if (ById('pbCatapult').checked==false) {
              ById('pbtargetCatapult').disabled = true;
          }
          else {
            ById('pbtargetCatapult').disabled = false;
          }
      },false);
      
        } else {
        
      
    	 } 
  t.timer = setTimeout (t.showAuto, 3000);   
  }, 
    getRallypoint: function(cityId){
        var t = Tabs.Reassign;
        for (var o in Seed.buildings[cityId]){
  		var buildingType = parseInt(Seed.buildings[cityId][o][0]);
  		var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
  		if (buildingType == 12) t.rallypointlevel=parseInt(buildingLevel);
  	   }  
  	},
        	  
      
  
  	e_reassignRoutes: function(){
        var t = Tabs.Reassign;
        var now = new Date();
        if (t.reassignState.running == true)    {
        	var now = new Date().getTime()/1000.0;
        	now = now.toFixed(0);
        	var last = Options.lastreassign;
         		if ( now > (parseInt(last) + (Options.reassigninterval*60))){
      			  t.checkdoReassign();
        		}
        }
        setTimeout(function(){ t.e_reassignRoutes();}, Options.reassigninterval*1000);
        
      },
      	
  	delReassignRoutes: function() {
      	
  		var t = Tabs.Reassign;
      	
  		t.reassignRoutes= [];
      
  	},
  	checkcoords : function (obj){
  		var t = Tabs.Reassign;
  		if(obj.id == 'pbok'){
  			t.check = true;
  			t.addReassignRoute();
  		}
  		return;			
  	},
  	addReassignRoute: function () {
  		var t = Tabs.Reassign;
  		var city = t.tcp.city.id;
  		if(t.tcpto.city == null)return;
  		if(t.tcp.city.id == t.tcpto.city.id)return;
  		t.check = false;
  		var SendSupplyTroop = ById('pbSupplyTroops').checked;
  		var SendMilitiaman = ById('pbMilitiaman').checked;
  		var SendScout = ById('pbScout').checked;
  		var SendPikeman = ById('pbPikeman').checked;
  		var SendSwordsman = ById('pbSwordsman').checked;
  		var SendArchers = ById('pbArcher').checked;
  		var SendCavalry = ById('pbCavalry').checked;
  		var SendHeavyCavalry = ById('pbHeavyCavalry').checked;
  		var SendSupplyWagons = ById('pbSupplyWagon').checked;
  		var SendBallista = ById('pbBallista').checked;
  		var SendBatteringRam = ById('pbBatteringRam').checked;
  		var SendCatapult = ById('pbCatapult').checked;
  		var SupplyTroop = ById('pbtargetSupplyTroops').value;
  		var Militiaman = ById('pbtargetMilitiaman').value;
  		var Scout = ById('pbtargetScout').value;
  		var Pikeman = ById('pbtargetPikeman').value;
  		var Swordsman = ById('pbtargetSwordsman').value;
  		var Archers = ById('pbtargetArcher').value;
  		var Cavalry = ById('pbtargetCavalry').value;
  		var HeavyCavalry = ById('pbtargetHeavyCavalry').value;
  		var SupplyWagons = ById('pbtargetSupplyWagon').value;
  		var Ballista = ById('pbtargetBallista').value;
  		var BatteringRam = ById('pbtargetBatteringRam').value;
  		var Catapult = ById('pbtargetCatapult').value;
  		var target_x = t.tcpto.city.x;
  		var target_y = t.tcpto.city.y;
  				
  		var lRE = t.reassignRoutes;
  			lRE.push({
  				city:				city,
  				target_x:			target_x,
  				target_y:			target_y,
  				SendSupplyTroop:	SendSupplyTroop,
  				SupplyTroop:		SupplyTroop,
  				SendMilitiaman:		SendMilitiaman,
  				Militiaman:			Militiaman,
  				SendScout:			SendScout,
  				Scout:				Scout,
  				SendPikeman: 		SendPikeman,
  				Pikeman: 			Pikeman,
  				SendSwordsman:		SendSwordsman,
  				Swordsman:			Swordsman,
  				SendArchers:		SendArchers,
  				Archers:			Archers,
  				SendCavalry: 		SendCavalry,
  				Cavalry: 			Cavalry,
  				SendHeavyCavalry:	SendHeavyCavalry,
  				HeavyCavalry:		HeavyCavalry,
  				SendSupplyWagons:	SendSupplyWagons,
  				SupplyWagons:		SupplyWagons,
  				SendBallista: 		SendBallista,
  				Ballista: 			Ballista,
  				SendBatteringRam:	SendBatteringRam,
  				BatteringRam:		BatteringRam,
  				SendCatapult:		SendCatapult,
  				Catapult:			Catapult,
  			});
  		ById('pbReassignDivD').style.background ='#99FF99';
  		setTimeout(function(){ (ById('pbReassignDivD').style.background =''); }, 1000);
  	},
  	showReassignRoutes: function () {
  		var t = Tabs.Reassign;
  		var popReassignRoutes = null;
  		t.popReassignRoutes = new CPopup('pbShowTrade', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
  		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowReassignRoutes" id="pbRoutesQueue">';       
  		t.popReassignRoutes.getMainDiv().innerHTML = '</table></div>' + m;
  		t.popReassignRoutes.getTopDiv().innerHTML = '<TD><B>Les routes :</td>';
  		t.paintReassignRoutes();
  		t._addTabHeader();
  		t.popReassignRoutes.show(true)	;
  	},
  	paintReassignRoutes: function(){
  	        var t = Tabs.Reassign;
  	        var r = t.reassignRoutes;
  	        var cityname;
  			for (var i = (r.length-1); i>=0; i--) {
  				for (var y=0; y< Seed.cities.length;y++) {
  					if ( parseInt(Seed.cities[y][0]) == r[i].city) var cityname = Seed.cities[y][1];
  				}    
  				var queueId = i;
  				t._addTab(queueId,cityname, r[i].target_x, r[i].target_y, r[i].SendSupplyTroop,r[i].SupplyTroop, r[i].SendMilitiaman, r[i].Militiaman, r[i].SendScout, r[i].Scout, r[i].SendPikeman, r[i].Pikeman, r[i].SendSwordsman, r[i].Swordsman, r[i].SendArchers, r[i].Archers, r[i].SendCavalry, r[i].Cavalry, r[i].SendHeavyCavalry, r[i].HeavyCavalry, r[i].SendSupplyWagons, r[i].SupplyWagons, r[i].SendBallista, r[i].Ballista, r[i].SendBatteringRam, r[i].BatteringRam, r[i].SendCatapult, r[i].Catapult);
  	        }
  	    },
  	  
  	 _addTab: function(queueId,cityname,target_x,target_y,SendSupplyTroop,SupplyTroop,SendMilitiaman,Militiaman,SendScout,Scout,SendPikeman,Pikeman,SendSwordsman,Swordsman,SendArchers,Archers,SendCavalry,Cavalry,SendHeavyCavalry,HeavyCavalry,SendSupplyWagons,SupplyWagons,SendBallista,Ballista,SendBatteringRam,BatteringRam,SendCatapult,Catapult){
  	 	var t = Tabs.Reassign;
  	     var row = ById('pbRoutesQueue').insertRow(0);
  	     row.vAlign = 'top';
  	     row.insertCell(0).innerHTML = queueId;
  	     row.insertCell(1).innerHTML = cityname;
  	     row.insertCell(2).innerHTML = target_x + ',' + target_y;
  	     row.insertCell(3).innerHTML = SendSupplyTroop;
  	     row.insertCell(4).innerHTML = addCommas(SupplyTroop);
  	     row.insertCell(5).innerHTML = SendMilitiaman;
  	     row.insertCell(6).innerHTML = addCommas(Militiaman);
  	 	 row.insertCell(7).innerHTML = SendScout;
  	 	 row.insertCell(8).innerHTML = addCommas(Scout);
  	 	 row.insertCell(9).innerHTML = SendPikeman;
  	 	 row.insertCell(10).innerHTML = addCommas(Pikeman);
  	 	 row.insertCell(11).innerHTML = SendSwordsman;
  	 	 row.insertCell(12).innerHTML = addCommas(Swordsman);
  	 	 row.insertCell(13).innerHTML = SendArchers;
  	 	 row.insertCell(14).innerHTML = addCommas(Archers);
  	 	 row.insertCell(15).innerHTML = SendCavalry;
  	 	 row.insertCell(16).innerHTML = addCommas(Cavalry);
  	 	 row.insertCell(17).innerHTML = SendHeavyCavalry;
  	 	 row.insertCell(18).innerHTML = addCommas(HeavyCavalry);
  	 	 row.insertCell(19).innerHTML = SendSupplyWagons;
  	 	 row.insertCell(20).innerHTML = addCommas(SupplyWagons);
  	 	 row.insertCell(21).innerHTML = SendBallista;
  	 	 row.insertCell(22).innerHTML = addCommas(Ballista);
  	 	 row.insertCell(23).innerHTML = SendBatteringRam;
  	 	 row.insertCell(24).innerHTML = addCommas(BatteringRam);
  	 	 row.insertCell(25).innerHTML = SendCatapult;
  	 	 row.insertCell(26).innerHTML = addCommas(Catapult);
  	     row.insertCell(27).innerHTML = '<a class="button20" id="tradecancel_' + queueId + '"><span>Effacer</span></a>';
  	     ById('tradecancel_' + queueId).addEventListener('click', function(){
  	        t.cancelQueueElement(queueId);
  	     }, false);
  	 },
  	 
  	 _addTabHeader: function() {
  	 var t = Tabs.TranspAuto;
  	     var row = ById('pbRoutesQueue').insertRow(0);
  	     row.vAlign = 'top';
  	     row.insertCell(0).innerHTML = "ID";
  	     row.insertCell(1).innerHTML = "Depuis";
  	     row.insertCell(2).innerHTML = "vers";
  	     row.insertCell(3).innerHTML = "Sup. Tr.";
  	     row.insertCell(4).innerHTML = "";
  	     row.insertCell(5).innerHTML = "MM";
  	     row.insertCell(6).innerHTML = "";
  	     row.insertCell(7).innerHTML = "Scouts";
  	     row.insertCell(8).innerHTML = "";
  	     row.insertCell(9).innerHTML = "Pike";
  	     row.insertCell(10).innerHTML = "";
  	     row.insertCell(11).innerHTML = "Swords";
  	     row.insertCell(12).innerHTML = "";
  	     row.insertCell(13).innerHTML = "Archers";
  	     row.insertCell(14).innerHTML = "";
  	     row.insertCell(15).innerHTML = "Cav.";
  	     row.insertCell(16).innerHTML = "";
  	     row.insertCell(17).innerHTML = "HC";
  	     row.insertCell(18).innerHTML = "";
  	     row.insertCell(19).innerHTML = "Wagons";
  	     row.insertCell(20).innerHTML = "";
  	     row.insertCell(21).innerHTML = "Ballista";
  	     row.insertCell(22).innerHTML = "";
  	     row.insertCell(23).innerHTML = "Rams";
  	     row.insertCell(24).innerHTML = "";
  	     row.insertCell(25).innerHTML = "Catapults";
  	     row.insertCell(26).innerHTML = "";
  	     row.insertCell(27).innerHTML = "Supp";
  	   },   
  	   
  	 cancelQueueElement: function(queueId){
  	     var t = Tabs.Reassign;
  	     var queueId = parseInt(queueId);
  	     t.reassignRoutes.splice(queueId, 1);
  	     t.showReassignRoutes();
  	 },
  	   
  	saveReassignRoutes: function(){
  		var t = Tabs.Reassign;
          var serverID = getServerId();
          GM_setValue('reassignRoutes_' + serverID, JSON2.stringify(t.reassignRoutes));
      },
      readReassignRoutes: function(){
          var t = Tabs.Reassign;
          var serverID = getServerId();
          s = GM_getValue('reassignRoutes_' + serverID);
          if (s != null) {
              route = JSON2.parse(s);
              for (k in route)
                  t.reassignRoutes[k] = route[k];
          }
      },
      saveReassignState: function(){
  		var t = Tabs.Reassign;
          var serverID = getServerId();
          GM_setValue('reassignState_' + serverID, JSON2.stringify(t.reassignState));
      },
      readReassignState: function(){
          var t = Tabs.Reassign;
          var serverID = getServerId();
          s = GM_getValue('reassignState_' + serverID);
          if (s != null) {
              state = JSON2.parse(s);
              for (k in state)
                  t.reassignState[k] = state[k];
          }
      },
      toggleReassignState: function(obj){
  		var t = Tabs.Reassign;
  	obj = ById('pbReassignState');
          if (t.reassignState.running == true) {
              t.reassignState.running = false;
              if (obj) obj.value = "Reassign  = OFF";
  		updatebotbutton('Reassign  - OFF', 'pbsigntab');
  			t.checkdoreassigntimeout = null;
  			t.count = 0;
  			  		  Options.lastreassign = 0;
			  		  saveOptions();	
  		 
          }
          else {
              t.reassignState.running = true;
              if (obj) obj.value = "Reassign  = ON";
  		updatebotbutton('Reassign  - ON', 'pbsigntab');
  			t.e_reassignRoutes();
          }
      },
  	
     checkdoReassign: function(){
  	var t = Tabs.Reassign;
  	t.doReassign(t.count);
  	t.count++;
  		if(t.count < t.reassignRoutes.length && t.reassignState.running){
  		  t.checkdoreassigntimeout = setTimeout(function() { t.checkdoReassign();}, 5000);
  		} else {
  		  var now = new Date().getTime()/1000.0;
  		  now = now.toFixed(0);
  		  Options.lastreassign = now;
  		  saveOptions();	
  		  t.count = 0;
  		}
  	},
      
      doReassign: function(count){
      	var t = Tabs.Reassign;
     		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
     		if(t.reassignRoutes.length==0) return;
     		var send=[];
     		var citytotal=0;
     		var totalsend=0;
  		params.u1 = 0;
  		params.u2 = 0;
  		params.u3 = 0;
  		params.u4 = 0;
  		params.u5 = 0;
  		params.u6 = 0;
  		params.u7 = 0;
  		params.u8 = 0;
  		params.u9 = 0;
  		params.u10 = 0;
  		params.u11 = 0;
  		params.u12 = 0;	
  				
     	 	var city = t.reassignRoutes[count]["city"];
     	 	var xcoord = t.reassignRoutes[count]["target_x"];
     	 	var ycoord = t.reassignRoutes[count]["target_y"];
      	
      	var cityID = 'city' + city;
  		if(!Cities.byID[city]) return;
  		var marching = getMarchInfoBOT(cityID);
      	t.getRallypoint(cityID);
  		if(t.rallypointlevel == 11) t.rallypointlevel = 15;
      	var maxsend = (t.rallypointlevel * 10000);
      	totalsend=0;
      	
      	var troopsselect=["SupplyTroop","Militiaman","Scout","Pikeman","Swordsman","Archers","Cavalry","HeavyCavalry","SupplyWagons","Ballista","BatteringRam","Catapult"];
      	for (k=0; k<troopsselect.length; k++) {
  			var citytroops = Seed.units[cityID]['unt'+(parseInt(k)+1)];
  			var marchtroops = marching.marchUnits[parseInt(k)+1];
  			citytotal = parseInt(citytroops) + parseInt(marchtroops);
  			if(t.reassignRoutes[count]['Send'+troopsselect[k]]==false) {continue; }
  			if(citytotal > t.reassignRoutes[count][troopsselect[k]]){
  				var sendtroops = parseInt(citytotal) - parseInt(t.reassignRoutes[count][troopsselect[k]]);
  				if (parseInt(sendtroops) > parseInt(citytroops)) sendtroops = citytroops;
  				if (parseInt(sendtroops) < 0) sendtroops = 0;
  				send[(parseInt(k)+1)] = sendtroops;
  				totalsend += send[(parseInt(k)+1)];
  				
  			}
  			if(totalsend > maxsend){
  				totalsend -= send[(parseInt(k)+1)];
  				send[(parseInt(k)+1)] = parseInt(maxsend-totalsend);
  				totalsend += send[(parseInt(k)+1)];
  				break;
  			}
         	}
      	
      	for (var zz=0; zz< Seed.cities.length;zz++) {
      		if ( parseInt(Seed.cities[zz][0]) == city) var cityname = Seed.cities[zz][1];
      	}
      	
    		params.cid= city;
  		params.type = "5";
  		params.kid=0;
  		params.xcoord = xcoord;
  		params.ycoord = ycoord;
  		params.u1 = send[1];
  		params.u2 = send[2];
  		params.u3 = send[3];
  		params.u4 = send[4];
  		params.u5 = send[5];
  		params.u6 = send[6];
  		params.u7 = send[7];
  		params.u8 = send[8];
  		params.u9 = send[9];
  		params.u10 = send[10];
  		params.u11 = send[11];
  		params.u12 = send[12];	
  		
     		if (totalsend >0) {
        		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                    method: "post",
                    parameters: params,
                    loading: true,
                    onSuccess: function (transport) {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unixTime();
                    var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                    					for(i = 0; i <= unitsarr.length; i++){
                    						if(params["u"+i]){
                    								unitsarr[i] = params["u"+i];
                    						}
                    					}
                    var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                    var currentcityid = city;
                    unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                    actionLog("Reassign","Depuis: " + cityname + " Vers : " + xcoord + ',' + ycoord + "    ->   "+uW.g_js_strings.commonstr.troops+" : " + totalsend);
                    } else {
                    actionLog("Reassign","<font color=red>" + transport.responseText + "</font>");
                    }
                    },
                    onFailure: function (transport) {actionLog("Reassign","<font color=red>" + transport.responseText + "</font>");}
            });
     	 }      
  	},
      show: function(){
  		var t = Tabs.Reassign;
      },
  	hide: function(){
          var t = Tabs.Reassign;
      },
      onUnload: function(){
          var t = Tabs.Reassign;
          if (!ResetAll) t.saveReassignRoutes();
  	  if (!ResetAll) t.saveReassignState();
    },
  showManuel: function() {
    var t = Tabs.Reassign;
    var ModelCity = {};
    var rownum = 0;
    var rownum2 = 0;
    function _row (name, row, noTotal){
          if (rownum++ % 2)
            style = '';
          else
            style = ' style = "background: #e8e8e8"';
          var tot = 0;
          var m = [];
          m.push ('<TR style="background: #fff" align=right');
          m.push (style);
          m.push ('><TD');
          m.push (style);
          m.push ('><B>');
          m.push (name);
          m.push ('</td>');
          if (noTotal){
            m.push ('<TD');
            m.push (style);
            m.push ('>&nbsp;</td>');
          } else {
            for (i=0; i<row.length; i++)
              tot += row[i];
            m.push ('<TD style="background: #ffc">');
            m.push (addCommas(tot));
            m.push ('</td>');
          }
          for (i=0; i<row.length; i++){
            m.push ('<TD');
            m.push (style);
            m.push ('>');
            m.push (addCommas(row[i]));
            m.push ('</td>');
          }
          m.push ('</tr>');
          return m.join('');
    }
    if (t.state == null) {  
      m = "<DIV class=boStat>R&eacute;assigner des troupes d'une ville a une autre</div>";
      m +="<div id='statpourREA'></div>";
      m += "<TABLE width='450px' class=ptTab border=0 align=left>\
        <tr align=center valign=middle><td colspan=1 width=100><b><u>Source</b></u><br><span id=REAsrcRptspeedcity></span></td>\
        <td colspan=1 width='100px'><input type=button style='font-weight:bold' id=REAaction value='R&eacute;assigner'></td>\
        <td colspan=1 width='100px'><b><u>Destination</b></u><br><span id=REAdesRptspeedcity></span></td><td width=150 colspan=1><b><u>Estimation Temps</b></u><br>&nbsp;Distance : <span id='BOEstimationREAD'>&nbsp;</span></td></tr>\
        <tr align=center valign=top><td width=100><div id=REAstatsource></div></td>\
        <td ><table cellspacing=0 cellpadding=0 width=99%>";
         for (r=1; r<13; r++){
         if (rownum++ % 2)
	             style = '';
	           else
            style = ' style = "background: #e8e8e8"';
	     m += '<tr '+style+'><td  align=right><img height=20 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="REAnbunit'+r+'" type=text size=7 value="0"></td></tr>';
   	}
   	     
        m += "</table></td><td><div id=REAstatdest></div></td>";
        m += "<td colspan=2><table cellspacing=0 cellpadding=0 width=80%>";
        for (r=1; r<13; r++){
        if (rownum++ % 2)
	            style = '';
	          else
            style = 'background: #e8e8e8;';
		    m += '<tr style="'+style+' height:16px;font-size:11px;"><td width=50% height=20 align=center><span id="BOEstimationREAZ'+r+'">&nbsp;</span></td></tr>';
   	}
      m += "</tr></table>";
      m += "</tr><tr><td colspan=4>Option : <SELECT id='REApiKnight' type=list></tr><tr><td colspan=4><div id='ptREAStatus' style='text-align:center;overflow-y:auto; max-height:30px; height: 30px;'></div></td></tr></table>";
      t.ReassignDiv.innerHTML = m; 
      t.statpourREA = document.getElementById ('statpourREA');
      t.statutREA = document.getElementById ('ptREAStatus');
      t.actionREA = document.getElementById ('REAaction');
      t.actionREA.addEventListener ('click', t.clickReassigneDo, false);
      var dcp1 = new CdispCityPicker ('ptREA1', ById('REAdesRptspeedcity'), false, t.clickREACityDestinationSelect, 1);
      var dcp0 = new CdispCityPicker ('ptREA0', ById('REAsrcRptspeedcity'), false, t.clickREACitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
      t.state = 1;
      t.estimerTemps();
    }
    rows = [];
    rows[0]=[];
    m = "<TABLE class=ptTabLined cellspacing=0><TR valign=top align=right><TD width=20></td><TD width=88 style='background: #ffc'><B>TOTAL</b></td>";
    for(i=0; i<Cities.numCities; i++) {
             m += '<TD width=81><B>'+ Cities.cities[i].name.substring(0,10) +'</b></td>';
    }
    for (r=1; r<13; r++){
            rows[r] = [];
            for(i=0; i<Cities.numCities; i++) {
              cityID = 'city'+ Cities.cities[i].id;
              rows[r][i] = parseInt(Seed.units[cityID]['unt'+r]);
            }
    }
    for (r=1; r<13; r++){
     m += _row ('<img height=18 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg>', rows[r]);
    }
     row = [];
    for(i=0; i<Cities.numCities; i++) {
    	        var cityId = 'city'+ Cities.cities[i].id;
    	        var slots = 0;
    	        for (var k in Seed.queue_atkp[cityId]){   
    	         march = Seed.queue_atkp[cityId][k];
    	         if (typeof (march) == 'object'){
    	           slots++;
    	         }
    	        }
	  var niveauPointRall=parseInt(getCityBuilding (Cities.cities[i].id, 12).maxLevel);t
	 if (niveauPointRall==12) niveauPointRall=11;
    	        row[i] = '<SPAN><B>'+ slots +'/'+ niveauPointRall +'</b></span>';
     }
    m += _row ('PR', row, true, 0);    
    m += "</table>";
    t.statpourREA.innerHTML = m;   
    clearTimeout (t.displayTimer);
    t.displayTimer = setTimeout (t.showManuel, 4000);
  },
  estimerTemps: function() {
       var t = Tabs.Reassign;
       var x1 = parseInt(t.sourceCity.x);
       var x2 = parseInt(t.destinationCity.x);
       var y1 = parseInt(t.sourceCity.y);
       var y2 = parseInt(t.destinationCity.y);
       var dist = distance (x1, y1, x2, y2);
       ById("BOEstimationREAD").innerHTML = "<b>" + dist + "</b>";     
       for (r=1; r<13; r++){
          var m = estETA(dist, r, t.sourceCity.id,5);
          ById("BOEstimationREAZ"+r).innerHTML = "<b>" + m.friendEtaStr + "</b>";
       }
    },
  clickReassigneDo: function() {
   var t = Tabs.Reassign;
   t.statutREA.innerHTML = '';
    var totalunit=0;
   for (r=1; r<13; r++){
       if (parseInt(ById("REAnbunit"+r).value) > parseInt(ById("REAdestunit"+r).value)) {
         ById("REAnbunit"+r).style.backgroundColor="red";
         return false;
       }
       totalunit=totalunit+parseInt(ById("REAnbunit"+r).value);
       ById("REAnbunit"+r).style.backgroundColor="";
   }
   if (t.sourceCity.id==t.destinationCity.id) {
         t.statutREA.innerHTML = '<FONT COLOR=#550000>Impossible sur les memes villes !.</font>';
        return;
   }
   if (totalunit==0) {
      t.statutREA.innerHTML = '<FONT COLOR=#550000>Impossible de reassigner avec 0 unit&eacute;e... pfff !.</font>';
        return;
   }
   var niveauPointRall=parseInt(getCityBuilding (t.sourceCity.id, 12).maxLevel);
         var maxtroupe=parseInt(niveauPointRall*10000);
         if (niveauPointRall==11) maxtroupe=150000;
         if (niveauPointRall==12) maxtroupe=200000;
   if (totalunit>maxtroupe) {
    t.statutREA.innerHTML = '<FONT COLOR=#550000>Impossible de reassigner plus de '+maxtroupe+' unit&eacute;es a la fois.</font>';
    return;
   }
  t.actionREA.disabled=true;
  var x=t.destinationCity.x;
  var y=t.destinationCity.y;
  var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  params.u1 = ById("REAnbunit1").value;
  params.u2 = ById("REAnbunit2").value;
  params.u3 = ById("REAnbunit3").value;
  params.u4 = ById("REAnbunit4").value;
  params.u5 = ById("REAnbunit5").value;
  params.u6 = ById("REAnbunit6").value;
  params.u7 = ById("REAnbunit7").value;
  params.u8 = ById("REAnbunit8").value;
  params.u9 = ById("REAnbunit9").value;;
  params.u10 = ById("REAnbunit10").value;
  params.u11 = ById("REAnbunit11").value;
  params.u12 = ById("REAnbunit12").value;	
  params.cid= t.sourceCity.id;
  params.type = "5";
  params.kid= ById("REApiKnight").value;
  params.xcoord = x;
  params.ycoord = y;
  t.statutREA.innerHTML ="<font size='2px'><b><i>Merci de patienter...</i></b></font>";
  new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
	method: "post",
	parameters: params,
	loading: true,
	onSuccess: function (transport) {
	 var t = Tabs.Reassign;
	 var rslt = transport;
	 if (rslt.ok) {
	  var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
	  var ut = unsafeWindow.unixtime();
    	  var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
	  for(i = 0; i <= unitsarr.length; i++){
	    if(params["u"+i]){	unitsarr[i] = params["u"+i];	}
	  }
	  var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
	  var currentcityid = t.sourceCity.id;
	  unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
	  if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
	  t.clickREACitySourceSelect(t.sourceCity);
	  t.statutREA.innerHTML ="<font size='2px'><b>R&eacute;assignation termin&eacute;e - Temps : " + timestr(timediff)+"</font>";
	  t.actionREA.disabled=false;
	 } else {
          t.statutREA.innerHTML ="<font color=red size='2px'>Erreur, merci de recommencer </font>";
          if (rslt.msg) {
           t.statutREA.innerHTML +="<br><font color=black size='2px'>" + rslt.msg +"</font>";
           t.actionREA.disabled=false;
          } else {
             t.statutREA.innerHTML +="<br>Tentative dans 2 secondes !</font>";
             setTimeout(function() { t.clickReassigneDo(); }, 2000);
          }
          
        }
       },
       onFailure: function () {
        var t = Tabs.Reassign;
         t.statutREA.innerHTML ="<font color=red>R&eacute;assignation en erreur....</font>";
         t.actionREA.disabled=false;
       }
    });
 },
 clickREACitySourceSelect : function (city){
   var t = Tabs.Reassign;
   var rownum=0;
   if (t.sourceCity!=city) {
         t.sourceCity = city; 
    for (r=1; r<13; r++){
     ById("REAnbunit"+r).value="0";
    }      
   } else {
    var cityID = 'city'+ t.sourceCity.id;
    for (r=1; r<13; r++){  
    
      if (parseInt(Seed.units[cityID]['unt'+r]) < ById("REAnbunit"+r).value)  ById("REAnbunit"+r).value="0";
    }
   }
   t.actionREA.disabled=false;
   var m="";
   m="<table cellspacing=0 cellpadding=0 width=80%>";
   var cityID = 'city'+ t.sourceCity.id;
   for (r=1; r<13; r++){  
       if (rownum++ % 2)
   	            style = '';
   	          else
            style = 'background: #e8e8e8;';
     m += '<tr style="'+style+'"><td align=right><img title="'+unsafeWindow.unitcost['unt'+r][0]+'" height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td>\
           <td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="REAdestunit'+r+'" type=text size=7 readonly value="'+parseInt(Seed.units[cityID]['unt'+r])+'">&nbsp;\
           <input type=button value=">" id="REApdestunit'+r+'"  style="border:1px solid black;height:16px;font-size:11px;"></td></tr>';
   }
   m += "</table>";
   ById("REAstatsource").innerHTML = m;
   var knt = new Array();
   ById('REApiKnight').innerHTML="";
   var o = document.createElement("option");
   o.text = uW.g_js_strings.modal_attack.dchooseknightd;
	  o.value = 0;
   	  ById("REApiKnight").options.add(o);
   	  for (k in Seed.knights['city' + t.sourceCity.id]){
          		if (Seed.knights['city' + t.sourceCity.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.sourceCity.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["politicsKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["combatKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["intelligenceKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"]){
          			knt.push ({
          				Name:   Seed.knights['city' + t.sourceCity.id][k]["knightName"],
          				Combat:	Seed.knights['city' + t.sourceCity.id][k]["combat"],
          				ID:	Seed.knights['city' + t.sourceCity.id][k]["knightId"],
          			});
          		}
          }
   knt = knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);}); 
   for (k in knt){
       			if (knt[k]["Name"] !=undefined){
   	    			var o = document.createElement("option");
   	    			o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +')')
   	    			o.value = knt[k]["ID"];
   	    			ById("REApiKnight").options.add(o);
       			}
   }
   for (r=1; r<13; r++){
     ById("REApdestunit"+r).addEventListener ('click', function() {
       var nomcha=this.id.replace("REApdest","REAdest");
       var nomcha2=this.id.replace("REApdestunit","REAnbunit");
       ById(nomcha2).value=0;
       var niveauPointRall=parseInt(getCityBuilding (t.sourceCity.id, 12).maxLevel);
         var maxtroupe=parseInt(niveauPointRall*10000);
         if (niveauPointRall==11) maxtroupe=150000;
         if (niveauPointRall==12) maxtroupe=200000;
       var nbunitto=0;
       for (r=1; r<13; r++) {
         nbunitto+=parseInt(ById("REAnbunit"+r).value);
       }
       var libre = parseInt(maxtroupe - nbunitto);
       if (ById(nomcha).value>=libre) {
         ById(nomcha2).value = libre;
       }  else {
         ById(nomcha2).value= ById(nomcha).value;
       }  
      }, false);
   }
   t.estimerTemps();
 },
 clickREACityDestinationSelect : function (city){
    var t = Tabs.Reassign;
    var rownum=0;
    t.destinationCity = city;
    var m="";
    m="<table cellspacing=0 cellpadding=0 width=80%>";
    for (r=1; r<13; r++){
       if (rownum++ % 2)
   	            style = '';
   	          else
            style = 'background: #e8e8e8;';
         cityID = 'city'+ t.destinationCity.id;
         m += '<tr style="'+style+'"><td align=right><img height=20 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" type=text size=7 readonly value="'+parseInt(Seed.units[cityID]['unt'+r])+'"></td></tr>';
    }
    m += "</table>";
    ById("REAstatdest").innerHTML = m;
    t.estimerTemps();
  },    
}
Tabs.ScoutAlliance = {
  tabOrder : 16,
  tabLabel: 'AutoScout',
  myDiv : null,
  MapAjax : new CMapAjax(),
  ScoutAllianceOptions : {
     num_scouts     : 1,
     min_might      : 500000,
     max_might      : 30000000,
     scout_interval : 5,
     scouting       : false,   
     scout_ready    : false,
     scoutage : {},
  },

  init : function (div){
    var t = Tabs.ScoutAlliance;
    var o = t.ScoutAllianceOptions;
    unsafeWindow.fetchAllianceMembers = t.eventGetMembers;
    t.myDiv = div;
    t.city = 0;
    t.citiesToScout = {};

    var s = GM_getValue('ScoutAllianceOptions_' + getServerId());
    if (s != null){
       t.ScoutAllianceOptions = JSON2.parse(s);   
    }

    for(var i=0; i < Cities.numCities; i++) {
        t.citiesToScout[i] = [];
        var s = GM_getValue('CitiesToScout_city_' + i + '_' + getServerId());
        if (s != null){
            t.citiesToScout[i] = JSON2.parse(s);   
        }
    }

    t.show();
    t.doNextScout();
  },


  setScoutAllianceOptions : function () {
     var t = Tabs.ScoutAlliance;
     GM_setValue ('ScoutAllianceOptions_' + getServerId(), JSON2.stringify(t.ScoutAllianceOptions));
  },

  show : function (){
    var t = Tabs.ScoutAlliance;
    var o = t.ScoutAllianceOptions;

    if (t.state == null){
      if (getMyAlliance()[0] == 0) {
        t.myDiv.innerHTML = '<BR><BR><CENTER>Vous devez faire partie d\'une alliance pour faire fonctionner cette onglet.</center>';
        t.state = 1;
        return;
      }
      var m = '<DIV class=boStat>AUTO-SCOUT D\'UNE ALLIANCE</div><DIV class=pbentry><TABLE width=100% cellpadding=0>';
         if (o.scouting) {
           m += '<TD><INPUT id=IdScoutingStatus type=submit value="AutoScout = ON"></td>';
         } else {
            if (o.scout_ready) {
               m += '<TD><INPUT id=IdScoutingStatus type=submit value="AutoScout = OFF"></td>';
            } else {
               m += '<TD><INPUT id=IdScoutingStatus type=submit value="AutoScout = Pas Pret"></td>';
            }
         }
         m += "<TR><TD colspan=1>ATTENTION : Le r&eacute;sultat se base sur le LeaderBoard, donc les donn&eacute;es ont 24h de retard !<br>ATTENTION : L'autoScout est brid&eacute; sur 1 scout toute les 24 heures par Coords !<br><b>MERCI DE NE PAS ABUSER DE CETTE FONCTION !</b></td></tr>";
         m += '<TR><TD>Interval Eclaireur : <INPUT id=IdScoutInterval type=text size=8 maxlength=8 value='+ o.scout_interval +' \> msecs</td>';
         m += '<TD>Nombre Eclaireur : <INPUT id=IdNumScouts disabled type=text size=8 maxlength=8 value='+ o.num_scouts +' \></td></tr>';
         m += '<TR><TD>'+uW.g_js_strings.commonstr.might+' Min : <INPUT id=IdMinMight type=text size=8 maxlength=8 value='+ o.min_might +' \></td>';
         m += '<TD>'+uW.g_js_strings.commonstr.might+' Max : <INPUT id=IdMaxMight type=text size=8 maxlength=8 value='+ o.max_might +' \></td></tr>';

         m += '<TR><TD class=xtab> Entrer un nom d\'alliance : &nbsp;</td>';
         m += '<TD class=xtab><INPUT id=IdSearchAllianceName type=text /> &nbsp;';
         m += '<INPUT id=IdSearchAllianceNameSubmit type=submit value="Rechercher Alliance" /></td></tr>';
         m += '<TR><TD class="xtab ptErrText"><SPAN id=IdScoutAllianceErrorSpan></span></td></tr>';
         m += '</table><span style="vertical-align:middle;" id=IdScoutAlliance></span></div>';
         m += '<div style="height:35px; max-height:35px;" id=IdScoutAllianceStatus></div></div>';
         m += '<div style="height:400px; max-height:400px; overflow-y:auto;"; id=IdScoutAllianceProgress></div></div>';
      t.myDiv.innerHTML = m;

      document.getElementById('IdScoutInterval').addEventListener('change', function(){
		o.scout_interval=parseInt(document.getElementById('IdScoutInterval').value);
		t.setScoutAllianceOptions();
	        },false);
      document.getElementById('IdNumScouts').addEventListener('change', function(){
		o.num_scouts=parseInt(document.getElementById('IdNumScouts').value);
		t.setScoutAllianceOptions();
	        },false);
      document.getElementById('IdMinMight').addEventListener('change', function(){
		o.min_might=parseInt(document.getElementById('IdMinMight').value);
		t.setScoutAllianceOptions();
	        },false);
      document.getElementById('IdMaxMight').addEventListener('change', function(){
		o.max_might=parseInt(document.getElementById('IdMaxMight').value);
		t.setScoutAllianceOptions();
	        },false);
      document.getElementById('IdSearchAllianceNameSubmit').addEventListener ('click', t.SearchAllianceSubmit, false);
      document.getElementById('IdScoutingStatus').addEventListener('click', function(){t.toggleScoutingStatus(this)} , false);
      t.state = 1;
    }
  },

  hide: function(){
  },

  SearchAllianceName : '',
  SearchAllianceSubmit : function (){
    var t = Tabs.ScoutAlliance;
    document.getElementById('IdScoutAllianceErrorSpan').innerHTML='';
    t.SearchAllianceName = document.getElementById('IdSearchAllianceName').value;
    if (t.SearchAllianceName.length < 3){
      document.getElementById('IdScoutAllianceErrorSpan').innerHTML = 'Besoin de 3 caracteres minimum';
      return;
    }
    document.getElementById('IdScoutAllianceStatus').innerHTML = '<DIV class=ptstat>Recherche encours <B>"'+ t.SearchAllianceName +'"</b>...';
    t.fetchAllianceList (t.SearchAllianceName, t.eventGotAllianceList);
  },

  eventGotAllianceList : function (rslt){
    var t = Tabs.ScoutAlliance;
    if (!rslt.ok){
      document.getElementById('IdScoutAllianceStatus').innerHTML = rslt.errorMsg;
      document.getElementById('IdScoutAllianceErrorSpan').innerHTML = rslt.errorMsg;
      return;
    }
    var m = '<DIV class=boStat>Alliances correspondant &agrave; <B>"'+ t.SearchAllianceName +'"</b></div>\
    <TABLE><TR style="font-weight:bold"><TD class=xtab>Nom</td><TD class=xtab>Rang</td><TD class=xtab>Membres</td>\
        <TD align=right class=xtab>Might</td><TD class=xtab>Diplomacie</td><TD class=xtab></td></tr>';
    for (k in rslt.alliancesMatched){
      var all = rslt.alliancesMatched[k];
      var dip = '';
      if (all.relation && all.relation==1)
        dip = 'amicale';
      else if (all.relation && all.relation==2)
        dip = 'hostile';
      m += '<TR><TD class=xtab>'+ all.allianceName +'</td><TD align=right class=xtab>'+ all.ranking +'</td><TD align=right class=xtab>'+ all.membersCount +'</td>\
       <TD align=right class=xtab>'+ addCommasInt(all.might) +'</td><TD class=xtab>'+ dip +'</td>\
       <TD class=xtab><a onclick="fetchAllianceMembers('+ all.allianceId +')">Eclairer les Members</a></td></tr>';
    }
    document.getElementById('IdScoutAllianceStatus').innerHTML = m;
  },

  fetchAllianceList : function (allianceName, notify) {
    var t = Tabs.ScoutAlliance;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.allianceName = allianceName;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetSearchResults.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
          notify (rslt);
      },
      onFailure: function (rslt) {
        notify ({errorMsg:'AJAX error'});
      },
    });
  },

  eventGetMembers : function (aid){
    var t = Tabs.ScoutAlliance;
    t.ScoutAllianceOptions.scout_ready = false;
    t.setScoutAllianceOptions();
    document.getElementById('IdScoutingStatus').value = "AutoScout = Pas pret";
    document.getElementById('IdScoutAllianceStatus').innerHTML = '<DIV class=ptstat>'+uW.g_js_strings.commonstr.loadingddd+'...';
    document.getElementById('IdScoutAllianceProgress').innerHTML = '';
    t.fetchAllianceMemberList (aid, t.eventGotMemberList);
  },

  fetchAllianceMemberList : function (allianceId, notify) {
    var t = Tabs.ScoutAlliance;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.perPage = 100;
    params.allianceId = allianceId;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify (rslt);
      },
      onFailure: function (rslt) {
        notify ({errorMsg:'AJAX error'});
      },
    });
  },

  eventGotMemberList : function (rslt){
    var t = Tabs.ScoutAlliance;
    var o = t.ScoutAllianceOptions;
    document.getElementById('IdScoutAllianceProgress').innerHTML="";
    if (!rslt.ok){
      document.getElementById('IdScoutAllianceStatus').innerHTML = rslt.errorMsg;
      document.getElementById('IdScoutAllianceErrorSpan').innerHTML = rslt.errorMsg;
      return;
    }
    var numInvalid = 0;
    var numPlayers = 0;
    var numCities = 0;
    var myA = getMyAlliance ();
    var dist = 0;
    for(var i=0; i < Cities.numCities; i++) {
        t.citiesToScout[i] = [];
    }
    for (var r=0; r<rslt.results.length; r++){
      p = rslt.results[r];
      if (p.userId == 0){
        ++numInvalid;
      } else {
        ++numPlayers;
        numCities += p.cities.length;
        might = parseInt(p.might);
        if (might > parseInt(o.min_might) && might < parseInt(o.max_might)) {
          for (var c=0; c<p.cities.length; c++){
             for(var i=0; i < Cities.numCities; i++) {
                dist = distance (Cities.cities[i].x, Cities.cities[i].y, p.cities[c].xCoord, p.cities[c].yCoord);
                t.citiesToScout[i].push ({x:p.cities[c].xCoord,y:p.cities[c].yCoord, dist:dist, nom:p.displayName});
            }
          }
        }
      }
    }

    dist = 100000;
    for(var i=0; i < Cities.numCities; i++) {
        t.citiesToScout[i].sort(function sortDist(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
        if (t.citiesToScout[0].length > 0 && t.citiesToScout[i][0].dist < dist) {
            t.city = i;
            dist = t.citiesToScout[i][0].dist;
        }
        GM_setValue('CitiesToScout_city_' + i + '_' + getServerId(), JSON2.stringify(t.citiesToScout[i]));
    }
    if (t.city == 0) t.city = Cities.numCities;
    else t.city -= 1;

    var m = ''; 
    m += '<DIV class=boStat>Recherche termin&eacute;e : '+ rslt.allianceName +' (trouv&eacute; ' + numPlayers + ' joueurs';
    if (numInvalid > 0) m += ' (' + numInvalid + 'sous brume ?)';
    m += ', ' +t.citiesToScout[0].length+ ' villes &agrave; &eacute;clairer';
    if (t.citiesToScout[0].length != numCities) m += ' (total ' + numCities + ')';
    m += ')</div><div>';
    document.getElementById('IdScoutAllianceStatus').innerHTML = m;
    if (t.citiesToScout[0].length > 0) {
      t.ScoutAllianceOptions.scout_ready = true;
      t.setScoutAllianceOptions();
      document.getElementById('IdScoutingStatus').value = "AutoScout = OFF";
    }
  },
  toggleScoutingStatus: function(obj){
     var t = Tabs.ScoutAlliance;
     var o = t.ScoutAllianceOptions;
     if (!o.scout_ready) return;
     if (o.scouting) {
         o.scouting = false;
         t.setScoutAllianceOptions();
         obj.value = "AutoScout = OFF";
         t.nextscout = null;
     } else {
         o.scouting = true;
         t.setScoutAllianceOptions();
         obj.value = "AutoScout = ON";
         t.doNextScout();
     }
  },
  doNextScout: function(){
     var t = Tabs.ScoutAlliance;
     var o = t.ScoutAllianceOptions;
     if (!o.scout_ready) return;
     if (!o.scouting) return;
     var slots = 0;
     var can_scout = false;
     that_city = t.city;
     var now = new Date().getTime()/1000.0;
     now = now.toFixed(0);		  
     do {
       t.city += 1;
       if (t.city>=Seed.cities.length){
	  t.city=0;
       }

       this_city = t.city;
       if (this_city == that_city) {
           t.nextscout = setTimeout(t.doNextScout,(parseInt(o.scout_interval)*1000));
           return;
       }

       city = Cities.cities[this_city];

       if (t.citiesToScout[this_city].length == 0) {
          o.scout_ready = false;
          o.scouting = false;
          t.setScoutAllianceOptions();
          document.getElementById('IdScoutingStatus').value = "AutoScout = Pas Pret";
          t.nextscout = null;
          return;
       }

       if(parseInt(Seed.units['city'+city.id]['unt'+3]) < parseInt(o.num_scouts)){
          continue;
       }

       var rallypointlevel = t.getRallypoint(city.id);
       if(rallypointlevel == 12) rallypointlevel = 11;
       slots = 0;
       if (Seed.queue_atkp['city'+city.id] != undefined){
	       for(var k in Seed.queue_atkp['city'+city.id])
		      slots++;
		      if(Seed.queue_atkp['city'+city.id].toSource() == "[]")
		          slots = 0;
	}
	  else slots=0;
	  
       id=t.citiesToScout[this_city][0].x+","+t.citiesToScout[this_city][0].y;
       if (t.ScoutAllianceOptions.scoutage[id]) {       
        last = t.ScoutAllianceOptions.scoutage[id];
        if ( now < (parseInt(last) + (24 * 60 * 60))){
         t.scout_delete(t.citiesToScout[this_city][0].x,t.citiesToScout[this_city][0].y);    
         
         continue;
        }
       } 
       if(slots >= rallypointlevel){
          continue; 
       }
       can_scout = true;

    } while (!can_scout);


      
	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = city.id;
	params.kid = 0;
	params.type = 3;
	params.xcoord = t.citiesToScout[this_city][0].x;
	params.ycoord = t.citiesToScout[this_city][0].y;
	params.u3 = parseInt(o.num_scouts);
	new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
		 method: "post",
		 parameters: params,
		 onSuccess: function (rslt) {
		 if (rslt.ok) {
			 var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
			 var ut = unixTime();
			 var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
			 var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
			 for(i = 0; i <= unitsarr.length; i++){
				if(params["u"+i]){
				unitsarr[i] = params["u"+i];
				}
			 }
			 var currentcityid = params.cid;
			 unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
			 if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
			 document.getElementById('IdScoutAllianceProgress').innerHTML += 'Eclaireur envoy&eacute; de '+city.name+' sur '+t.citiesToScout[this_city][0].nom+' '+params.xcoord+', '+params.ycoord+' - Distance : '+t.citiesToScout[this_city][0].dist+'<BR>';
                         t.scout_done(params.xcoord, params.ycoord);
                         t.nextscout = setTimeout(t.doNextScout,(o.scout_interval*1000));
		 } else {
                         rslt.errorMsg = unsafeWindow.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null));
			 document.getElementById('IdScoutAllianceProgress').innerHTML += 'Echec d\'envoi de '+city.name+' sur '+t.citiesToScout[this_city][0].nom+' '+params.xcoord+', '+params.ycoord+' ['+rslt.errorMsg+']<BR>';
                          if (rslt.error_code==208) t.scout_done(params.xcoord, params.ycoord);                        
                         t.nextscout = setTimeout(t.doNextScout,(o.scout_interval*1000));
		  }
		},
		onFailure: function () {}
  		});
  },

 getRallypoint: function(cityId){
      var t = Tabs.ScoutAlliance;
      cityId = 'city'+cityId;
      for (o in Seed.buildings[cityId]){
		var buildingType = parseInt(Seed.buildings[cityId][o][0]);
		var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
		if (buildingType == 12){
			return parseInt(buildingLevel);
			break;
		}
	   }
	  return 0;
    },
  scout_delete : function(x,y) {
    var t = Tabs.ScoutAlliance;
    var id = x + "," + y;
    
    for(var i=0; i < Cities.numCities; i++) {
     for (var c=0; c < (t.citiesToScout[i].length); c++) {
       if (parseInt(t.citiesToScout[i][c].x) == parseInt(x) && parseInt(t.citiesToScout[i][c].y) == parseInt(y)) {
             t.citiesToScout[i].splice(parseInt(c), 1);
       }
     }
    }
   document.getElementById('IdScoutAllianceProgress').innerHTML += 'Eclaireur '+t.citiesToScout[this_city][0].nom+' sur '+x+', '+y+' - <b>Restriction 24h !</b><BR>';
     
  },
  scout_done: function(x,y){
     var t = Tabs.ScoutAlliance;
     var cnt = 0;
     for(var i=0; i < Cities.numCities; i++) {
       for (var c=0; c < (t.citiesToScout[i].length); c++) {
         if (parseInt(t.citiesToScout[i][c].x) == parseInt(x) && parseInt(t.citiesToScout[i][c].y) == parseInt(y)) {
           var now = new Date().getTime()/1000.0;
	   now = now.toFixed(0);
	   var id = x + "," + y;
           t.ScoutAllianceOptions.scoutage[id] = now;
           t.setScoutAllianceOptions();
           t.citiesToScout[i].splice(parseInt(c), 1);
           GM_setValue('CitiesToScout_city_' + i + '_' + getServerId(), JSON2.stringify(t.citiesToScout[i]));
           cnt++;
           break;
         }
       }
    }
    if (cnt != Cities.numCities) {
    }
  },
}

Tabs.autoFormation= {
 tabOrder: 9,
 tabLabel: 'AutoForm',
 cont : null,
 nbfil : 0,
 crfil : 0,
 timer:null,
 city : 0,
 numcity :-1,
 init : function (div){
   var t = Tabs.autoFormation;
   t.cont = div;
   t.state = null;
   AddSubTabLink('Formation', t.toggleautoFormationState, 'pbformtab');
   if (TrainOptions.Running == false) {
      updatebotbutton('Form - OFF', 'pbformtab');
   } else {
      updatebotbutton('Form - ON', 'pbformtab');
      t.timer=setTimeout(t.Start,5000);
   }
   if (TrainOptions.timelauch<5) { 
    TrainOptions.timelauch=5;
    saveTrainingOptions();
   
   }
   return t.cont;
  },
 Start: function() {
  var t = Tabs.autoFormation;
  if (!TrainOptions.Running) {
    clearTimeout(t.timer);
    return;
  }
  if (t.numcity<Cities.numCities-1) {
      t.numcity++;
    } else {
     t.numcity=-1; 
     clearTimeout(t.timer);
     
     t.timer=setTimeout(t.Start,parseIntNan(TrainOptions.timelauch*60)*1000);
     return;
  }
  var c=t.numcity;
  var cityId=Cities.cities[c].id;
  if (!TrainOptions.listactif[cityId]) t.Start();
  var populationdispo = 0;
  if(!TrainOptions.listlabour[cityId]) {
   populationdispo = parseIntNan(Seed.citystats['city'+cityId].pop[0]) - parseIntNan(Seed.citystats['city'+cityId].pop[3]);	
  }else {
    populationdispo = parseIntNan(Seed.citystats['city'+cityId].pop[0]).toFixed(0); 
  }
  var availableTrainingSlots = 0;
  try{
   	var barracksTotal = getCityBuilding(cityId, 13).count;
   	var trainingSlotsUsed = Seed.queue_unt['city'+cityId].length;
   	if(trainingSlotsUsed!=null){
   	  availableTrainingSlots = barracksTotal-trainingSlotsUsed;
   	}
  }finally{
	
   } 
   maxunite = t.unitemax(cityId, TrainOptions.list[Cities.cities[c].id],(c+1));
   var resources = t.checkresources(cityId, c);
   if (!resources) {
    actionLog("AutoForm",Cities.cities[c].name+ " - ERREUR : Ressources - possible de faire : "+maxunite+"/"+parseInt(TrainOptions.unitemin[Cities.cities[c].id]));     
    return;
   }  
   if(availableTrainingSlots>0 && maxunite>=parseIntNan(TrainOptions.unitemin[Cities.cities[c].id]) && TrainOptions.listactif[Cities.cities[c].id]) {
       var unitId = TrainOptions.list[cityId]; 
       var num = parseInt(maxunite);
       if (TrainOptions.unitemax[Cities.cities[c].id] != undefined) {
        var maxnum = TrainOptions.unitemax[Cities.cities[c].id];
        if (num>parseInt(TrainOptions.unitemax[Cities.cities[c].id])) num=parseInt(TrainOptions.unitemax[Cities.cities[c].id]);
       }
       var gam= TrainOptions.listboost[cityId];
       var time = unsafeWindow.modal_barracks_traintime(unitId, num);
         var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
         params.cid = cityId;
         params.type = unitId;
         params.quant = num;
         params.items = 0;
         params.gambleId = gam;
         new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/train.php" + unsafeWindow.g_ajaxsuffix, {
           method: "post",
           parameters: params,
           loading: true,
           onSuccess: function(transport) {
            var rslt = eval("(" + transport.responseText + ")");
             if (rslt.ok) {
               var resourceFactors=[],resourceLost;
	              if(gam!=null){
	                time=rslt.timeNeeded;
	       	      }
	               for(var i=1;i<5;i++){
	               if(rslt.gamble){
	                resourceFactors.push(rslt.gamble[i.toString()]);
	               }else{
	               resourceFactors.push(1);
	               }
	               resourceLost=parseInt(unsafeWindow.unitcost["unt"+unitId][i])*3600*parseInt(num);resourceLost=resourceLost*resourceFactors[i-1];
	               unsafeWindow.seed.resources["city"+cityId]["rec"+i][0]=parseInt(unsafeWindow.seed.resources["city"+cityId]["rec"+i][0])-resourceLost;
       }
   unsafeWindow.seed.citystats["city"+cityId].gold[0]=parseInt(unsafeWindow.seed.citystats["city"+cityId].gold[0])-parseInt(unsafeWindow.unitcost["unt"+unitId][5])*parseInt(num);
         unsafeWindow.seed.citystats["city"+cityId].pop[0]=parseInt(unsafeWindow.seed.citystats["city"+cityId].pop[0])-parseInt(unsafeWindow.unitcost["unt"+unitId][6])*parseInt(num);
         unsafeWindow.seed.queue_unt["city"+cityId].push([unitId,num,rslt.initTS,parseInt(rslt.initTS)+time,0,time,null]);
         
	if(rslt.updateSeed) { unsafeWindow.update_seed(rslt.updateSeed) }
         actionLog("AutoForm",Cities.cities[c].name+" - " + num+" "+unsafeWindow.unitcost['unt'+ TrainOptions.list[Cities.cities[c].id]][0]+" OK");
             } else {
              actionLog("AutoForm",Cities.cities[c].name+ " - " + num+" "+unsafeWindow.unitcost['unt'+ TrainOptions.list[Cities.cities[c].id]][0]+"<br><font color=red>" + transport.responseText +"</font>");
             }
           },
           onFailure: function(o) {
            actionLog("AutoForm",Cities.cities[c].name+ " - " + num+" "+unsafeWindow.unitcost['unt'+ TrainOptions.list[Cities.cities[c].id]][0]+"<br><font color=red>" +o.responseText+"</font>");
           }
  	});
   } else {  
    if (availableTrainingSlots<=0) {
       actionLog("AutoForm",Cities.cities[c].name+ " - ERREUR : Slot non dispo");  
    }
    if (maxunite<parseInt(TrainOptions.unitemin[Cities.cities[c].id])) {
       actionLog("AutoForm",Cities.cities[c].name+ " - ERREUR : Population ou Ressource - possible de faire : "+maxunite+"/"+parseInt(TrainOptions.unitemin[Cities.cities[c].id]));     
    }
   }
   
   var cityNo = t.numcity + 1;
   		if (TrainOptions.doTraps[cityNo])
   			t.doAutoTraps(cityNo);
   		if (TrainOptions.doCalrops[cityNo])
   			t.doAutoCaltrops(cityNo);
   		if (TrainOptions.doSpikes[cityNo])
   			t.doAutoSpikes(cityNo);
   		if (TrainOptions.doXbows[cityNo])
			t.doAutoCrossbows(cityNo);
   		if (TrainOptions.doTrebu[cityNo])
			t.doAutoTrebu(cityNo);
			

    clearTimeout(t.timer);
    t.timer=setTimeout(function() { t.Start(); },5000);
 
 },
 doAutoTraps: function (cityNo) {
 		var t = Tabs.autoFormation;
 		wall = {};
 		var cityId = Cities.cities[cityNo - 1].id
 		var cityID = 'city'+ cityId;
 		getWallInfo (cityId, wall);
 		availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
 		if (availableSpace > 0 && wall.slotsBusy < 3) {
 			var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
 			var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
 			var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
 			var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
 			availableSlots = 3 - wall.slotsBusy;
 			var foodRes = TrainOptions.keepFood[cityNo];
 			var woodRes = TrainOptions.keepWood[cityNo];
 			var stoneRes = TrainOptions.keepStone[cityNo];
 			var oreRes = TrainOptions.keepOre[cityNo];
 			var availFood = food - foodRes;
 			var availWood = wood - woodRes;
 			var availStone = stone - stoneRes;
 			var availOre = ore - oreRes;
 		        secsPerTrap = Cities.byID[cityId]['Def60Time'];
 			if (secsPerTrap > 0 && availableSpace > 4 && availableSlots > 0) {
 				if (availFood > 400 && availWood > 800 & availStone > 200 & availOre > 400) {
 					var numberToTrain = 9999999999;
 					if ((availFood / 400) < numberToTrain)
 						numberToTrain = parseInt(availFood / 400);
 					if ((availWood / 800) < numberToTrain)
 						numberToTrain = parseInt(availWood / 800);
 					if ((availStone / 200) < numberToTrain)
 						numberToTrain = parseInt(availStone / 200);
 					if ((availOre / 400) < numberToTrain)
 						numberToTrain = parseInt(availOre / 400);
 					if (numberToTrain > 5)
 						numberToTrain = 5;
 					if (wall.Trap + wall.TrapTraining < 10 || availableSpace < 15) {
 						numberToTrain = 1;
 					} 
 					actionLog("AutoForm",Cities.byID[cityId].name + ' - Construction ' + numberToTrain + ' piege ');
 					doDefTrain (cityId, 0, 60, numberToTrain);
 				}
 			}
 		}
  },
 doAutoCaltrops: function (cityNo) {
 		var t = Tabs.autoFormation;
 		var wall = {};
 		var cityId = Cities.cities[cityNo - 1].id;
 		var cityID = 'city'+ cityId;
 		getWallInfo (cityId, wall);
 		availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
 		if (availableSpace > 0 && wall.slotsBusy < 3) {
 			var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
 			var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
 			var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
 			var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
 			availableSlots = 3 - wall.slotsBusy;
 			var foodRes = TrainOptions.keepFood[cityNo];
 			var woodRes = TrainOptions.keepWood[cityNo];
 			var stoneRes = TrainOptions.keepStone[cityNo];
 			var oreRes = TrainOptions.keepOre[cityNo];
 			var availFood = food - foodRes;
 			var availWood = wood - woodRes;
 			var availStone = stone - stoneRes;
 			var availOre = ore - oreRes;
 			secsPerCaltrop = Cities.byID[cityId]['Def61Time'];
 			if (secsPerCaltrop > 0 && availableSpace > 1 && availableSlots > 0) {
 				if (availFood > 100 && availOre > 400) {
 					var numberToTrain = 9999999999;
 					if ((availFood / 100) < numberToTrain)
 						numberToTrain = parseInt(availFood / 100);
 					if ((availOre / 400) < numberToTrain)
 						numberToTrain = parseInt(availOre / 400);
 					if (numberToTrain > 5)
 						numberToTrain = 5;
 					if (wall.Caltrops + wall.CaltropsTraining < 10 || availableSpace < 15) {
 						numberToTrain = 1;						
 					}
 					actionLog("AutoForm",Cities.byID[cityId].name + ' - Construction ' + numberToTrain + ' chausse-trape ');
 					doDefTrain (cityId,0,61,numberToTrain); 					
 				}
 			}
 		}
	},
	doAutoSpikes: function (cityNo) {
		var t = Tabs.autoFormation;
		wall = {};
		var cityId = Cities.cities[cityNo - 1].id
		var cityID = 'city'+ cityId;
		getWallInfo (cityId, wall);
		availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
		if (availableSpace > 0 && wall.slotsBusy < 3) {
			var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
			var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
			var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
			var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
			availableSlots = 3 - wall.slotsBusy;
			var foodRes = TrainOptions.keepFood[cityNo];
			var woodRes = TrainOptions.keepWood[cityNo];
			var stoneRes = TrainOptions.keepStone[cityNo];
			var oreRes = TrainOptions.keepOre[cityNo];
			var availFood = food - foodRes;
			var availWood = wood - woodRes;
			var availStone = stone - stoneRes;
			var availOre = ore - oreRes;
			secsPerSpike = Cities.byID[cityId]['Def62Time'];
			if (secsPerSpike > 0 && availableSpace > 3 && availableSlots > 0) {
				if (availFood > 150 && availWood > 750 & availStone > 50) {
					var numberToTrain = 9999999999;
					if ((availFood / 150) < numberToTrain)
						numberToTrain = parseInt(availFood / 150);
					if ((availWood / 750) < numberToTrain)
						numberToTrain = parseInt(availWood / 750);
					if ((availStone / 50) < numberToTrain)
						numberToTrain = parseInt(availStone / 50);
					if (numberToTrain > 5)
						numberToTrain = 5;
					if (wall.SpikedBarrier + wall.SpikedBarrierTraining < 10 || availableSpace < 15) {
						numberToTrain = 1;
					} 
					actionLog("AutoForm",Cities.byID[cityId].name + ' - Construction ' + numberToTrain + ' palissade ');
					doDefTrain (cityId, 0, 62, numberToTrain);
				}
			}
		}
	},
	doAutoCrossbows: function (cityNo) {
		var t = Tabs.autoFormation;
		wall = {};
		var cityId = Cities.cities[cityNo - 1].id
		var cityID = 'city'+ cityId;
		getWallInfo (cityId, wall);
		availableSpace = wall.wallSpace - wall.wallSpaceUsed;
		if (availableSpace > 0 && wall.slotsBusy < 2) {
			var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
			var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
			var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
			var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
			availableSlots = 2 - wall.slotsBusy;
			var foodRes = TrainOptions.keepFood[cityNo];
			var woodRes = TrainOptions.keepWood[cityNo];
			var stoneRes = TrainOptions.keepStone[cityNo];
			var oreRes = TrainOptions.keepOre[cityNo];
			var availFood = food - foodRes;
			var availWood = wood - woodRes;
			var availStone = stone - stoneRes;
			var availOre = ore - oreRes;
			secsPerXbow = Cities.byID[cityId]['Def53Time'];
			if (secsPerXbow > 0 && availableSpace > 2 && availableSlots > 0) {
				if (availFood > 250 && availWood > 2000 & availStone > 750 & availOre > 500) {
					var numberToTrain = 9999999999;
					if ((availFood / 250) < numberToTrain)
						numberToTrain = parseInt(availFood / 250);
					if ((availWood / 2000) < numberToTrain)
						numberToTrain = parseInt(availWood / 2000);
					if ((availStone / 750) < numberToTrain)
						numberToTrain = parseInt(availStone / 750);
					if ((availOre / 500) < numberToTrain)
						numberToTrain = parseInt(availOre / 500);
					if (numberToTrain > 5)
						numberToTrain = 5;
					if (wall.Crossbows + wall.CrossbowsTraining < 10 || availableSpace < 15) {
						numberToTrain = 1;
					} 
					actionLog("AutoForm",Cities.byID[cityId].name + ' - Construction ' + numberToTrain + ' arbaletes ');
					doDefTrain (cityId, 0, 53, numberToTrain);
				}
			}
		}
	},
	doAutoTrebu: function (cityNo) {
		var t = Tabs.autoFormation;
		wall = {};
		var cityId = Cities.cities[cityNo - 1].id
		var cityID = 'city'+ cityId;
		getWallInfo (cityId, wall);
		availableSpace = wall.wallSpace - wall.wallSpaceUsed;
		if (availableSpace > 0 && wall.slotsBusy < 2) {
			var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
			var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
			var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
			var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
			availableSlots = 2 - wall.slotsBusy;
			var foodRes = TrainOptions.keepFood[cityNo];
			var woodRes = TrainOptions.keepWood[cityNo];
			var stoneRes = TrainOptions.keepStone[cityNo];
			var oreRes = TrainOptions.keepOre[cityNo];
			var availFood = food - foodRes;
			var availWood = wood - woodRes;
			var availStone = stone - stoneRes;
			var availOre = ore - oreRes;
			secsPerTrebu = Cities.byID[cityId]['Def55Time'];
			if (secsPerTrebu > 0 && availableSpace > 4 && availableSlots > 0) {
				if (availFood > 500 && availWood > 3500 & availStone > 1800 & availOre > 1200) {
					var numberToTrain = 9999999999;
					if ((availFood / 500) < numberToTrain)
						numberToTrain = parseInt(availFood / 500);
					if ((availWood / 3500) < numberToTrain)
						numberToTrain = parseInt(availWood / 3500);
					if ((availStone / 1800) < numberToTrain)
						numberToTrain = parseInt(availStone / 1800);
					if ((availOre / 1200) < numberToTrain)
						numberToTrain = parseInt(availOre / 1200);
					if (numberToTrain > 5)
						numberToTrain = 5;
					if (wall.Trebuchet + wall.TrebuchetTraining < 10 || availableSpace < 15) {
						numberToTrain = 1;
					} 
					actionLog("AutoForm",Cities.byID[cityId].name + ' - Construction ' + numberToTrain + ' trebuchet ');
					doDefTrain (cityId, 0, 55, numberToTrain);
				}
			}
		}
	},
 unitemax : function(currentcityid, e, numcity){
 
 var gumble = TrainOptions.listboost[currentcityid];
 var mult=1;
 if (gumble==0) mult=1;
 if (gumble==1) mult=2;
 if (gumble==2) mult=4;
 var b=new Array();
 var a=new Array();
 for(var d=1;d<5;d++){
  b.push((parseInt(unsafeWindow.unitcost["unt"+e][d])*3600)*mult);
  a.push(parseInt(unsafeWindow.seed.resources["city"+currentcityid]["rec"+d][0]))
 }
  b.push((parseInt(unsafeWindow.unitcost["unt"+e][5]))*mult);
  a.push(parseInt(unsafeWindow.seed.citystats["city"+currentcityid].gold[0]));
  b.push((parseInt(unsafeWindow.unitcost["unt"+e][6])));

  if (!TrainOptions.listlabour[currentcityid]) {
    a.push(parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[0])-parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[3]));
  } else {
    a.push(parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[0])-parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[3])+ parseInt((parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[3])*(TrainOptions.Workers[numcity]/100))));
  }  
  var c=a[0]/b[0];
  for(var d=1;d<b.length;d++)
  {
    if(parseInt(b[d])!=0){
     c=Math.min(c,a[d]/b[d])
    }
  }
  if (c<0) c=0
  return parseInt(c)||0
 },
 hide : function (){
    var t = Tabs.autoFormation;
    t.saveOptionsAutoF(); 
  },

  show : function (){  
    var t = Tabs.autoFormation;
    unsafeWindow.BO_AF_TU_Change = t.AF_TU_Change;
    m = "<DIV class=boStat>FORMATIONS AUTOMATIQUE DE TROUPES - REMPARTS - <input type=button value='?' id=boaideautoform class=boAide></div>";
    m += '<div style="height:' + (Options.HauteurBoite-60) +'px;max-height:' + (Options.HauteurBoite-60) +'px;overflow-y:auto"><TABLE width=720 class=ptTab border=0 align=center><tr align=center valign=top><TD>';
    if (TrainOptions.Running == false) {
       m += '<INPUT id=autoFormationtoggle type=submit value="Formation AUTO = OFF">';
    } else {
       m += '<INPUT id=autoFormationtoggle type=submit value="Formation AUTO = ON">';
    }
    m+="&nbsp;<INPUT id=autoMilicienstoggle type=submit value='Mode : '><select id=BOModeFA>";
    for (r=2; r<13; r++){
     m+= "<option value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
    }
    m+="</select></td></tr></table>";
    m += "<TABLE width=100% class=ptTab border=0 align=center cellspacing=0 cellpadding=1>\
          <tr align=center><td align=center style='border-bottom:1px solid black' colspan=2><b>"+uW.g_js_strings.commonstr.city+"</td>\
          <td align=center style='border-bottom:1px solid black'><b>Type Unit&eacute;</td>\
          <td align=center style='border-bottom:1px solid black'><b>Unit&eacute; Min</td>\
          <td align=center style='border-bottom:1px solid black'><b>Unit&eacute; Max</td>\
          <td align=center style='border-bottom:1px solid black' colspan=2><a id=BO_WorkersCalc><b>"+uW.g_js_strings.showPopTooltip.lbrforce+"</a></td>\
          <tD align=center style='border-bottom:1px solid black'><b>Boost</td></tr>";
    var city=0;
    for (var c=0; c<Cities.numCities; c++) {
     cityId=Cities.cities[c].id;  
     city = c+1;
     m+="<tr><td rowspan=3 width=10% align=left style='border-bottom:1px solid black'><b>"+(c+1)+"</b> : "+Cities.cities[c].name+"<br></td><td align=right rowspan=3 style='border-bottom:1px solid black'>";
     if (TrainOptions.listactif && TrainOptions.listactif[cityId] == false) {
      m+="<input type=checkbox id='autoFCheck_"+cityId+"'>";
     }else {
      m+="<input checked type=checkbox id='autoFCheck_"+cityId+"'>";
     }
     m+="</td><TD align=center><SELECT id='autoFType_"+cityId+"' onchange='BO_AF_TU_Change("+cityId+",this.value);'>";
     for (r=1; r<13; r++){
      var faux = 0;
      var uc = unsafeWindow.unitcost['unt'+r];
      if (matTypeof(uc[8]) == 'object'){
            for (k in uc[8]){  
              var b = getCityBuilding (cityId, k.substr(1));
              if (b.maxLevel < uc[8][k][1]){
                faux = 1;
                break;
              }
            }
          }
          if (matTypeof(uc[9]) == 'object'){
            for (k in uc[9]){
              if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
 	       faux = 1;
                break;
              }
            }
         }
       if (faux==0) {
	if (TrainOptions.list) {
	   if (r==TrainOptions.list[cityId]) {
		     	               m+= "<option selected value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
           } else {
		     	               m+= "<option value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
	   }
	}else{
	   if (r==2) {
	               m+= "<option selected value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
	              } else {
	               m+= "<option value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
	   }
       }
      } 
    } 
    if (TrainOptions.unitemax[Cities.cities[c].id] == undefined) TrainOptions.unitemax[Cities.cities[c].id] = 999999;
    if (isNaN(parseInt(TrainOptions.unitemin[cityId]))) TrainOptions.unitemin[cityId]=0 ;
    if (TrainOptions.Keep[city] == undefined) TrainOptions.Keep[city] ={};
    m+= "</select></td><td align=left><input type=text value='"+ parseIntNan(TrainOptions.unitemin[cityId]) +"' id='aFunitemin_"+cityId+"' size=4></td><td align=left><input type=text value='"+ parseIntNan(TrainOptions.unitemax[cityId]) +"' id='aFunitemax_"+cityId+"' size=5></td><td align=right>";
    if (TrainOptions.listlabour && TrainOptions.listlabour[cityId] == false) {
         m+="<input type=checkbox class="+city+" id='autoFWorkers_"+cityId+"'>";
    }else {
         m+="<input checked class="+city+" type=checkbox id='autoFWorkers_"+cityId+"'>";
    }
    m+="</td><td align=right>";
    m+='<SELECT class='+city+' id="workers'+city+'"><option value="0">0%</options>';
    m+='<option value="25">25%</options><option value="50">50%</options><option value="75">75%</options><option value="100">100%</options></select></td><td align=right>';
    m+="<select id='autoFboost_"+cityId+"'>";
    m+="<option value=0>Normal</option><option value=1 "+ (TrainOptions.listboost[cityId]==1?'SELECTED ':'') +">5-15%</option><option value=2 "+ (TrainOptions.listboost[cityId]==2?'SELECTED ':'') +">10-25%</option></select>";
    m+="</td></tr>"; 
    m+='<TR><td colspan=6><img width=23 src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/food_30.png">&nbsp;';
    m += '<INPUT class='+city+'  id="KeepFood'+city+'" type=text size=7 maxlength=8 value="'+ parseIntNan(TrainOptions.Keep[city]['Food'])+'"\>&nbsp;';
    m += '<img width=23 src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/wood_30.png">&nbsp;';
    m += '<INPUT class='+city+' id="KeepWood'+city+'" type=text size=7 maxlength=8 value="'+ parseIntNan(TrainOptions.Keep[city]['Wood'])+'"\>&nbsp;';
    m += '<img width=23 src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/stone_30.png">&nbsp;';
    m += '<INPUT class='+city+'  id="KeepStone'+city+'" type=text size=7 maxlength=8 value="'+ parseIntNan(TrainOptions.Keep[city]['Stone'])+'"\>&nbsp;';
    m += '<img width=23 src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/iron_30.png">&nbsp;';
    m += '<INPUT class='+city+' id="KeepOre'+city+'" type=text size=7 maxlength=8 value="'+ parseIntNan(TrainOptions.Keep[city]['Ore'])+'"\>';
    m += "</td></tr><TR><td colspan=8 style='border-bottom:1px solid black'>Auto-Rempart : <INPUT class="+city+" type=CHECKBOX id='chkDoTraps"+city+"' "+ (TrainOptions.doTraps[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt60[0]+"&nbsp;\
        	<INPUT class="+city+" type=CHECKBOX id='chkDoCaltrops"+city+"' "+ (TrainOptions.doCalrops[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt61[0]+"&nbsp;\
        	<INPUT class="+city+" type=CHECKBOX id='chkDoSpikes"+city+"' "+ (TrainOptions.doSpikes[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt62[0]+"&nbsp;\
        	<INPUT class="+city+" type=CHECKBOX id='chkDoXbows"+city+"' "+ (TrainOptions.doXbows[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt53[0].substr(0,9)+"&nbsp;\
       	<INPUT class="+city+" type=CHECKBOX id='chkDoTrebu"+city+"' "+ (TrainOptions.doTrebu[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt55[0]+"</TD></TR>";

    }
    m+="</table><table width=100% class=ptTab border=0><tr><td><u>Options divers :</u><br>Interval de formation : <input id=aFtimelauch type=text size=2 value='"+parseInt(TrainOptions.timelauch)+"'> minutes (enregistrer et rafraichir pour prise en compte)\
         <br>Pourcentage de la population (total) par d&eacute;faut pour calculer la zone -Unit&eacute; min- : <select id=BOModeDiv><option value=25>25%</option><option value=50>50%</option><option value=75>75%</option><option value=90>90%</option><option value=100>100%</option></select> - <input type=button value='Tout recalculer' id=BO_AllCalculate>'";	   
    m+="<br><br><b>Auto-rempart</b> : Construction en automatique d'une d&eacute;fense pour atteindre un maximum de 5.</td></tr>\
    <tr><td><u>Annulation automatique des formations en cours :</u><br><input type=checkbox id=BO_AF_CancelFirst> Supprimer la formation en cours</td><td><input type=button value='"+uW.g_js_strings.modaltitles.deleteall+"' id=BO_AF_CancelAll></td></tr>\
    <tr><td><span id='BO_AF_Progression'></span></td></tr></table></div><br>";
   
    t.cont.innerHTML = m; 
     ById('boaideautoform').addEventListener('click', function(){
    	       	 window.open(sitesupport+"?page=aide_autoform");
    	} , false);
    for (i=0;i<Seed.cities.length;i++){
            city = i+1;
            ById('workers'+city).value = TrainOptions.Workers[city];     
    }
    ById('BOModeDiv').value=TrainOptions.UnitMixValue;
    ById('BOModeDiv').addEventListener('change', function(e){
      TrainOptions.UnitMixValue=ById('BOModeDiv').value;
      for (var c=0; c<Cities.numCities; c++) {
           		cityId=Cities.cities[c].id; 
                      t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);          
      }
     
    },false);
    ById('BO_WorkersCalc').addEventListener('click', function(){
     t.workers();
    } , false);
    ById('BO_AllCalculate').addEventListener('click', function(){
        for (var c=0; c<Cities.numCities; c++) {
     		cityId=Cities.cities[c].id; 
                t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);          
      	}
      	
    } , false);
    ById('autoFormationtoggle').addEventListener('click', function(){t.toggleautoFormationState(this)} , false);
    ById('autoMilicienstoggle').addEventListener('click', function(){t.milicien()} , false);
    ById('BO_AF_CancelAll').addEventListener('click', function(){t.AF_CancelAll()} , false);
    t.dispStatus = ById('BO_AF_Progression');
    var k=0;
    window.addEventListener('unload', t.onUnload, false);
    for (var c=0; c<Cities.numCities; c++) {
    	  k=c+1;
    	  cityID=Cities.cities[c].id;
    	  ById('autoFWorkers_'+cityID).addEventListener('click', function(e){  
    	   
    	   cityId=Cities.cities[(e.target['className']-1)].id; 
    	   TrainOptions.listlabour[cityId] = ById('autoFWorkers_'+cityId).checked;
	   t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value); 
	   
    	  },false);
    	  
    	  
    	  ById('workers'+k).addEventListener('change', function(e){   
	   TrainOptions.Workers[e.target['className']] = e.target.value;
	   cityId=Cities.cities[(e.target['className']-1)].id; 
    	   t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value); 
	      
      	  }, false);
      	  
    	 ById('chkDoTraps'+k).addEventListener('click', function(e){
    			TrainOptions.doTraps[e.target['className']] = e.target.checked;
         		saveTrainingOptions();
		}, false);
	ById('chkDoCaltrops'+k).addEventListener('click', function(e){
    			TrainOptions.doCalrops[e.target['className']] = e.target.checked;
         		saveTrainingOptions();
		}, false);	
	ById('chkDoSpikes'+k).addEventListener('click', function(e){
    			TrainOptions.doSpikes[e.target['className']] = e.target.checked;
         		saveTrainingOptions();
		}, false);
       ById('chkDoXbows'+k).addEventListener('click', function(e){
    			TrainOptions.doXbows[e.target['className']] = e.target.checked;
         		saveTrainingOptions();
		}, false);
	 ById('chkDoTrebu'+k).addEventListener('click', function(e){
    			TrainOptions.doTrebu[e.target['className']] = e.target.checked;
         		saveTrainingOptions();
		}, false);	
		ById('KeepFood'+k).addEventListener('change', function(e){
			if (isNaN(e.target.value)) e.target.value=0 ;
            TrainOptions.Keep[e.target['className']]['Food'] = e.target.value;
            saveTrainingOptions();
      	}, false);
      	ById('KeepWood'+k).addEventListener('change', function(e){
      	    if (isNaN(e.target.value)) e.target.value=0 ;
            TrainOptions.Keep[e.target['className']]['Wood'] = e.target.value;
            saveTrainingOptions();
      	}, false);
      	ById('KeepStone'+k).addEventListener('change', function(e){
			if (isNaN(e.target.value)) e.target.value=0 ;
            TrainOptions.Keep[e.target['className']]['Stone'] = e.target.value;
            saveTrainingOptions();
      	}, false);
      	ById('KeepOre'+k).addEventListener('change', function(e){
      	    if (isNaN(e.target.value)) e.target.value=0 ;
            TrainOptions.Keep[e.target['className']]['Ore'] = e.target.value;
            saveTrainingOptions();
      	}, false);
    } 	
  },
  unload:function() {
   var t = Tabs.autoFormation;
   saveTrainingOptions();
  },
  checkresources : function(cityId, city){
  	var t = Tabs.autoFormation;
  	var city=city+1;
  	t.food = parseInt((Seed.resources['city'+cityId].rec1[0]/3600) - parseIntNan(TrainOptions['Keep'][city]['Food']));
  	t.wood = parseInt((Seed.resources['city'+cityId].rec2[0]/3600) - parseIntNan(TrainOptions['Keep'][city]['Wood']));
  	t.stone = parseInt((Seed.resources['city'+cityId].rec3[0]/3600) - parseIntNan(TrainOptions['Keep'][city]['Stone']));
  	t.ore = parseInt((Seed.resources['city'+cityId].rec4[0]/3600) - parseIntNan(TrainOptions['Keep'][city]['Ore']));
  	if(t.food>0 && t.wood>0 && t.stone>0 && t.ore>0){
  		return true;
  	}
  	return false;
  },
    AF_TU_Change: function(cityId,unit) {
     var t = Tabs.autoFormation;
     var coutenpop= unsafeWindow.unitcost['unt'+unit][6];
     var numcity=Cities.byID[cityId].idx+1;
     var X = Seed.citystats['city'+cityId]["pop"][1];
     var Y = unsafeWindow.seed.citystats["city"+cityId].pop[3];
     var Q= coutenpop;
     var Z = 0;
     var M = ById("BOModeDiv").value/100;
     if (ById("autoFWorkers_"+cityId).checked) {
        Z = ById('workers'+numcity).value/100;     
        ById("aFunitemax_"+cityId).value = parseIntNan(X/Q);
     } else {
      Z = 0;
      ById("aFunitemax_"+cityId).value=parseIntNan((X-Y)/Q);
     }
     var Min =((X-(Y*(1-Z)))*M)/Q;
     if (Min<0) Min=0;
     ById("aFunitemin_"+cityId).value = parseIntNan(Min);
     if (ById("aFunitemax_"+cityId).value<0) { ById("aFunitemax_"+cityId).value=0;ById("aFunitemin_"+cityId).value =0; }
     t.saveOptionsAutoF();
  },
 
  workers:function() {
   var t = Tabs.autoFormation;
   for (var c=0; c<Cities.numCities; c++) { 
    if (ById('workers'+(c+1)).value == "100") 
     ById('workers'+(c+1)).value = "25"
    else 
     ById('workers'+(c+1)).value = "100";
    
    TrainOptions.Workers[(c+1)] = ById('workers'+(c+1)).value ;
    cityId=Cities.cities[c].id; 
    t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value); 
   } 
   t.saveOptionsAutoF();   
  },
  milicien: function() {
   var t = Tabs.autoFormation;
   var typeunite = ById('BOModeFA').value;
   ById('BOModeDiv').value="90";
   var coutenpop= unsafeWindow.unitcost['unt'+typeunite][6];
   for (var c=0; c<Cities.numCities; c++) {    
    cityId=Cities.cities[c].id;  
    ById("autoFWorkers_"+Cities.cities[c].id).checked=true;
    ById("autoFCheck_"+Cities.cities[c].id).checked=true;
    ById("autoFType_"+Cities.cities[c].id).value=typeunite;  
    t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value); 
   }
   for (var c=0; c<Cities.numCities; c++) {
        cityId=Cities.cities[c].id; 
        t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);          
   }
   t.saveOptionsAutoF();
  },
  saveOptionsAutoF: function() {
     var t = Tabs.autoFormation;
     if (parseIntNan(ById('aFtimelauch').value) < 5)  ById('aFtimelauch').value = "5";
     TrainOptions.timelauch=ById('aFtimelauch').value;
     TrainOptions.UnitMixValue=ById('BOModeDiv').value;
     TrainOptions.list={};
     TrainOptions.listactif={};
     TrainOptions.listlabour={};
     TrainOptions.unitemin={};
     TrainOptions.unitemax={};
     TrainOptions.listboost={};
     for (var c=0; c<Cities.numCities; c++) {
        TrainOptions.list[Cities.cities[c].id] = ById('autoFType_'+Cities.cities[c].id).value;
        TrainOptions.listactif[Cities.cities[c].id] = ById('autoFCheck_'+Cities.cities[c].id).checked;
        TrainOptions.listlabour[Cities.cities[c].id] = ById('autoFWorkers_'+Cities.cities[c].id).checked;
        TrainOptions.unitemin[Cities.cities[c].id]=parseIntNan(ById('aFunitemin_'+Cities.cities[c].id).value);
        TrainOptions.unitemax[Cities.cities[c].id]=parseIntNan(ById('aFunitemax_'+Cities.cities[c].id).value);
        TrainOptions.listboost[Cities.cities[c].id]=ById('autoFboost_'+Cities.cities[c].id).value;
        TrainOptions.Workers[(c+1)] = ById('workers'+(c+1)).value;
     }
     saveTrainingOptions();
  },
  toggleautoFormationState : function(obj) {
     var t = Tabs.autoFormation;
     obj = ById('autoFormationtoggle');
     if (TrainOptions.Running == true) {
              TrainOptions.Running = false;
              clearTimeout(t.timer);
              if (obj) obj.value = "FormationAUTO = OFF";
              updatebotbutton('Form - OFF', 'pbformtab');
              saveTrainingOptions();
      }  else {
              TrainOptions.Running = true;
              clearTimeout(t.timer);
              t.numcity=-1; 
              t.timer=setTimeout(t.Start,5000);
              if (obj) obj.value = "FormationAUTO = ON";
              updatebotbutton('Form - ON', 'pbformtab');
              saveTrainingOptions();
      }
   },
    CancelActionall: function(numville, num, fintraitement) {
       
        var t = Tabs.autoFormation;
        var first=1;
        var cityId = Cities.cities[numville].id;
        var q = Seed.queue_unt['city'+cityId];
        var now = unixTime();
        start = q[num][2];
        end = q[num][3];
        actual = end - now;
        if (actual < 0) actual = 0;    
        var param2=cityId; 
        var param3=q[num][0];
        var param4=q[num][1]; 
        var param5=end;t
        var param6=start;
        var param7=actual;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
             params.cityId = param2;
             params.requestType ="CANCEL_TRAINING";
             params.numtrptrn = param4;
             params.trnETA= param5;
             params.trnNeeded = param7;
             params.trnTmp = param6;
             params.typetrn= param3;
         
          new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelTraining.php" + unsafeWindow.g_ajaxsuffix, {
                  method: "post",
                  parameters: params,
                onSuccess: function (rslt) {
                 var t = Tabs.autoFormation;
                 if (rslt.ok) {
                    unsafeWindow.update_seed_ajax(true,function(){
        	       var k=0;for(var j=0;j<unsafeWindow.seed.queue_unt["city"+param2].length;j++){
        	        if(j>num){
        	         unsafeWindow.seed.queue_unt["city"+param2][j][2]=parseInt(rslt.dateTraining[k]["start"]);
        	         unsafeWindow.seed.queue_unt["city"+param2][j][3]=parseInt(rslt.dateTraining[k]["end"]);
        	         k++;
        	         }
        	        }
        	        unsafeWindow.seed.queue_unt["city"+param2].splice(num,1);
        	        for(var i=1;i<5;i++){
        	         var totalReturn=parseInt(unsafeWindow.unitcost["unt"+param3][i])*parseInt(param4)*3600/2;
        	         unsafeWindow.seed.resources["city"+param2]["rec"+i][0]=parseInt(unsafeWindow.seed.resources["city"+param2]["rec"+i][0])+totalReturn;
        	        }
        
            	});
                   t.crfil++;
     		ById('BO_AF_Progression').innerHTML = "<b><i>Supression en cours : " + t.crfil+ " / " +t.nbfil +"</i></b>";
     	        var numnew = num - 1;
     	        if (numnew<fintraitement) {
   		  		 if (numville==Cities.numCities) {
   		  		  ById('BO_AF_Progression').innerHTML = "<font color=#880000><B>Termine... Actualiser le jeu et lancer vos formations pour le tournoi !</b></font>";
   		  		  return;
   		  		 }
   		  		 numville++;
   		  		   		 var cityId = Cities.cities[numville].id;
   				 		 var q = Seed.queue_unt['city'+cityId];
   				   		 numnew=q.length-1;
   				   		if (q.length<=fintraitement) {
   				   		 ById('BO_AF_Progression').innerHTML = "<font color=#550000><B>ERREUR : Merci de recommencer.</b></font>";
   				   		 return;
   		  		}
   		  		 setTimeout(function (){
   				    t.CancelActionall(numville, numnew, fintraitement);
   		  		 }, (Math.random()*100)+100 );
   		  	        } else {
   		  	          setTimeout(function (){
   		  	            t.CancelActionall(numville, numnew, fintraitement);
   		  		  }, (Math.random()*100)+100 );
                    } 
                  
                 } else {
                  ById('BO_AF_Progression').innerHTML = "<font color=#550000><B>ERREUR : Impossible d'annuler les formations...<br>Actualisez le jeu et recommencer.</b></font>";
                 }
                },
                onFailure: function (rslt) {
                 var t = Tabs.autoFormation;
                 ById('BO_AF_Progression').innerHTML = "<font color=#550000><B>ERREUR : Impossible d'annuler les formations...<br>Actualisez le jeu et recommencer.</b></font>";
                }
         });
         
     },
     AF_CancelAll: function() {
      var t = Tabs.autoFormation;
      t.nbfil=0;
      t.crfil=0;
      var debutsup = 1;
      if ( ById('BO_AF_CancelFirst').checked) {  
       var debutsup=0 ;
      }
       for(i=0; i<Cities.numCities; i++) {
        var cityId = Cities.cities[i].id;
        var q = Seed.queue_unt['city'+cityId];
        t.nbfil += q.length - debutsup;
       }
      for(i=0; i<Cities.numCities; i++) {
       var cityId = Cities.cities[i].id;
       var q = Seed.queue_unt['city'+cityId];
       if (q.length>debutsup) {
        obj = ById('autoFormationtoggle');
        TrainOptions.Running = false;
        if (obj) obj.value = "FormationAUTO = OFF";
        updatebotbutton('Form - OFF', 'pbformtab');
        saveTrainingOptions();
        t.CancelActionall(i, q.length-1, debutsup);
        return false;
       }
      }
  },
}

/*************************************** FORMATION ***********************************************/
Tabs.Train = {
  tabOrder: 8,
  tabLabel: uW.g_js_strings.commonstr.train,
  cont : null,
  timer : null,
  state : null,
  stats : {},
  selectedCity : {},
  sourceCity : {},
  destinationCity : {},

  show : function (){
   var t = Tabs.Train;
    t.displayCityStats();
            t.changeTroopSelect();
         t.changeDefSelect();
   
   t.timer = setTimeout (t.show, 4000);
  },

  hide : function (){
    var t = Tabs.Train;
    clearTimeout (t.timer);
  },
  renvoyer : function(typeunit, cityId) {
   var t = Tabs.Train;
   var qte = parseInt(Seed.citystats["city"+cityId]["pop"][1]);
   var a=prompt("Renvoyer les unites - "+unsafeWindow.unitcost['unt'+typeunit][0]+" - Quantite ?", qte);
   if (parseInt(a)>0) {
     a = parseInt(a);
     nbcity = Seed.units["city"+cityId]["unt"+typeunit];
     if (a<=nbcity) {""
     
     
     var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
           params.cid = cityId;
           params.quant = a;
           params.type = typeunit;
               new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/dismissUnits.php" + unsafeWindow.g_ajaxsuffix, {
     	        method: "post",
     	        parameters: params,
	        onSuccess: function (rslt) {
                 if (rslt.ok){
     		  Seed.units["city"+cityId]["unt"+typeunit]=parseInt(Seed.units["city"+cityId]["unt"+typeunit])-parseInt(a);
                 }
       		},
			        onFailure: function (rslt) {
			          t.listeFavoris.innerHTML="<option>Erreur</option>";
			        },
    	});

    }
   }
   

  
  },
  init : function (div){
    var t = Tabs.Train;
    t.cont = div;
    unsafeWindow.BOcancelTraining = t.cancelTrainingBO;
    unsafeWindow.BOcancelFort = t.butcancelFort;
    unsafeWindow.BoRenvoyer = t.renvoyer;
  
    if (t.state == null){
   
      s = "<DIV id=trainTopSelect >\
        <DIV class=boStat>Former des troupes et construire des d&eacute;fenses sur les remparts</div><DIV style='height:10px'></div><DIV class=ptentry>\
        <DIV style='text-align:center; margin-bottom:10px;'>"+unsafeWindow.g_js_strings.commonstr.city+" : &nbsp; <span id=ptspeedcity></span></div>\
        <TABLE class=ptTab width=100%><TR valign=top><TD width=50%>\
        <TABLE align=center><TR><TD align=right>"+uW.g_js_strings.commonstr.troops+" : </td><TD colspan=2>\
        <SELECT id=ptttType>";
         for (r=1; r<13; r++){
         if (r==2) {
          s+= "<option selected value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
         } else {
          s+= "<option value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
         }
        } 
        if (Seed.items.i36){tutel1=Seed.items.i36}else{tutel1=0};
        if (Seed.items.i37){tutel2=Seed.items.i37}else{tutel2=0};
        if (Seed.items.i38){tutel3=Seed.items.i38}else{tutel3=0};
        if (Seed.items.i26){siege1=Seed.items.i26}else{siege1=0};
       s+= " </select> <br> (max <span id=ptttSpMax></span>)</td></tr>\
        <TR><TD align=right>par slot de </td><TD><INPUT id='ptttInpPS' size=5 type='text' value='0'\></td>\
          <TD><INPUT id='ptttButMaxPS' type=submit value='max'\> &nbsp; (max <span id=ptttSpMaxPS>0</span>)</td></tr>\
        <TR><TD align=right>sur</td><TD><INPUT id='ptttInpSlots' size=2 type='text' value='1'\> slots</td>\
          <TD width=75%><INPUT id='ptttButMaxSlots' type=submit value='max'\> &nbsp; (max <span id=ptttSpMaxSlots>1</span>)</td></tr>\
        <TR><TD align=right valign=top>"+uW.g_js_strings.showPopTooltip.lbrforce+" : </td><TD colspan=2><INPUT type=CHECKBOX id=chkPop"+ (Options.maxIdlePop?' CHECKED ':'') +">\
        - Boost: <SELECT id=BOGamble>\
        <option value='0'>Normal</option>\
        <option value='1'>5% - 15%</option>\
        <option value='2'>10% - 25%</option>\
        </select>\
        <br><SELECT id=tutelage>\
		<option value='0'><CENTER>--- "+unsafeWindow.g_js_strings.commonstr.speedup+" ---</center></option>\
		<option value='36'>"+ unsafeWindow.itemlist.i36.name+" ("+tutel1+")</option>\
        <option value='37'>"+ unsafeWindow.itemlist.i37.name+" ("+tutel2+")</option>\
        <option value='38'>"+ unsafeWindow.itemlist.i38.name+" ("+tutel3+")</option>\
		</select>\</td></tr>\
        <TR><TD colspan=3 align=center><DIV style='height:10px'></div><INPUT id='ptttButDo' type=submit value='"+unsafeWindow.g_js_strings.modal_openBarracks.trainttl+"'\>\
        <br><span id='BOmodal_barracks_traintime'>"+uW.g_js_strings.modal_barracks_trainingtab.esttime+" :</span></td></tr>\
        </table></td><TD width=20></td><TD style='border-left:solid 2px;' width=50% align=center>\
        <TABLE align=center><TR><TD align=right>"+unsafeWindow.g_js_strings.commonstr.defense+": </td><TD colspan=2>\
      <SELECT id=pttdType>\
        <option value='53'>"+unsafeWindow.fortcost.frt53[0]+"</option>\
        <option value='55'>"+unsafeWindow.fortcost.frt55[0]+"</option>\
        <option value='60'>"+unsafeWindow.fortcost.frt60[0]+"</option>\
        <option value='61'>"+unsafeWindow.fortcost.frt61[0]+"</option>\
        <option value='62'>"+unsafeWindow.fortcost.frt62[0]+"</option>\
      </select> <br> (<span id=pttdSpMax></span>)</td></tr>\
        <TR><TD align=right># par slot de </td><TD><INPUT id='pttdInpPS' size=5 type='text' value='0'\></td>\
          <TD><INPUT id='pttdButMaxPS' type=submit value='max'\> (max <span id=pttdSpMaxPS>0</span>)</td></tr>\
        <TR><TD align=right># sur </td><TD><INPUT id='pttdInpSlots' size=2 type='text' value='1'\> slots</td>\
          <TD width=75%><INPUT id='pttdButMaxSlots' type=submit value='max'\> (max <span id=pttdSpMaxSlots>1</span>)</td></tr>\
        <TR align=center><TD colspan=3><SPAN id=pttdSpace></span></td></tr>\
         <TR><TD colspan=3 align=center><DIV style='height:10px'>\
      <SELECT id=siege>\
      <option value='0'><CENTER>--- "+unsafeWindow.g_js_strings.commonstr.speedup+" ---</center></option>\
      <option value='26'>"+ unsafeWindow.itemlist.i26.name+" ("+siege1+")</option>\
      </select></div>\
      <BR><INPUT id='pttdButDo' type=submit value='"+unsafeWindow.g_js_strings.modal_openWalls.builddefenses+"'\>\
      <br><span id='BOmodal_barracks_deftime'>"+uW.g_js_strings.modal_barracks_trainingtab.esttime+" :</span> </td></tr></table>\
        </td></tr></table></div></div>\
        <TABLE align=center width=425 class=ptTab><TR><TD><div id=ptTrainStatus style='overflow-y:auto; max-height:70px; height: 70px;'></div></td></tr></table>\
        <div style='height: "+(Options.HauteurBoite-240)+"pxpx; max-height:"+(Options.HauteurBoite-240)+"pxpx; overflow-y:auto'>\
        <br><TABLE width=100% class=ptTab><TR><TD colspan=3><DIV id=divSTtop></div></td></tr>\
        <TR><TD width=50% style='padding-left:5px; padding-right:5px'><DIV style='text-align:center'><div class=boStat><img id=BOCancelAllTrain valign=absmiddle border=0 title='Annuler toutes les formations' src='http://cdn1.iconfinder.com/data/icons/musthave/16/Remove.png'>&nbsp;&nbsp;<B>Les troupes &nbsp; (<SPAN id=statTTtot></span>)</b></span></div></div><DIV id=divSTleft style='padding:5px; -moz-box-shadow:inset 0px 0px 5px #000; overflow-y: auto; height:"+(Options.HauteurBoite-590)+"px; max-height:"+(Options.HauteurBoite-590)+"px'></div></td>\
          <TD width=50% style='padding-left:5px; padding-right:5px'><DIV style='text-align:center'><div  class=boStat><B>Les d&eacute;fenses &nbsp; (<SPAN id=statDTtot></span>)</b></div></div><DIV id=divSTright style='padding:5px; -moz-box-shadow:inset 0px 0px 5px #000; overflow-y: auto; height:"+(Options.HauteurBoite-590)+"px; max-height:"+(Options.HauteurBoite-590)+"px'></div></td></tr>\
        </div></div>";
      t.cont.innerHTML = s;

      var dcp = new CdispCityPicker ('ptspeed', ById('ptspeedcity'), true, t.clickCitySelect, 0);
      t.TTspMax = document.getElementById ('ptttSpMax');
      t.BOGamble = document.getElementById ('BOGamble');
      t.TTspMaxPS = document.getElementById ('ptttSpMaxPS');
      t.TTspMaxSlots = document.getElementById ('ptttSpMaxSlots');
      t.TTbutMaxSlots = document.getElementById ('ptttButMaxSlots');
      t.TTbutMaxPerSlot = document.getElementById ('ptttButMaxPS');
      t.TTinpPerSlot = document.getElementById ('ptttInpPS');
      t.TTinpSlots = document.getElementById ('ptttInpSlots');
      t.TTselType = document.getElementById ('ptttType');
      t.TTbutDo = document.getElementById ('ptttButDo');
      t.TDspMax = document.getElementById ('pttdSpMax');
      t.TDspMaxPS = document.getElementById ('pttdSpMaxPS');
      t.TDspMaxSlots = document.getElementById ('pttdSpMaxSlots');
      t.TDbutMaxSlots = document.getElementById ('pttdButMaxSlots');
      t.TDbutMaxPerSlot = document.getElementById ('pttdButMaxPS');
      t.TDinpPerSlot = document.getElementById ('pttdInpPS');
      t.TDinpSlots = document.getElementById ('pttdInpSlots');
      t.TDselType = document.getElementById ('pttdType');
      t.TDbutDo = document.getElementById ('pttdButDo');
      t.TDspSpace = document.getElementById ('pttdSpace');
      t.divTrainStatus = document.getElementById ('ptTrainStatus');
            
      t.TTinpSlots.addEventListener ('change', t.updateTopTroops, false);
      t.BOGamble.addEventListener ('change', t.changeTroopSelect, false);
      t.TTbutMaxPerSlot.addEventListener ('click', t.clickTroopMaxPS, false);
      t.TTbutMaxSlots.addEventListener ('click', t.clickTroopMaxSlots, false);
      t.TTselType.addEventListener ('change', t.changeTroopSelect, false);
      t.TTbutDo.addEventListener ('click', t.clickTroopDo, false);
      t.TDinpSlots.addEventListener ('change', t.updateTopDef, false);
      t.TDselType.addEventListener ('change', t.changeDefSelect, false);
      t.TDbutMaxPerSlot.addEventListener ('click', t.clickDefMaxPS, false);
      t.TDbutMaxSlots.addEventListener ('click', t.clickDefMaxSlots, false);
      t.TDbutDo.addEventListener ('click', t.clickDefDo, false);
      
      document.getElementById ('BOCancelAllTrain').addEventListener ('click', t.CancelAllTraining, false);
      
      document.getElementById ('chkPop').addEventListener ('change', t.clickCheckIdlePop, false);
      
      t.state = 1;
    }


  },


/*******  TROOPS  ******/  
  
  updateTopTroops : function (){
    var t = Tabs.Train;
    var slots = parseInt(t.TTinpSlots.value, 10);
    if (isNaN(slots) || slots<0)
      slots = 0;
    t.TTspMax.innerHTML = t.stats.MaxTrain;
    t.TTspMaxSlots.innerHTML = t.stats.barracks - t.stats.queued;
    if (slots<1 || (t.stats.barracks-t.stats.queued < 1))
      t.TTspMaxPS.innerHTML = 0;
    else
      t.TTspMaxPS.innerHTML = parseInt(t.stats.MaxTrain / slots);
  },
      
  
  clickTroopMaxPS : function (){
    var t = Tabs.Train;
    var slots = parseInt(t.TTinpSlots.value, 10);
    if (slots<1 || (t.stats.barracks-t.stats.queued < 1))
      t.TTinpPerSlot.value = 0;
    else
      t.TTinpPerSlot.value = parseInt(t.stats.MaxTrain / slots);
  },

  clickTroopMaxSlots : function (){
    var t = Tabs.Train;
    t.TTinpSlots.value = t.stats.barracks - t.stats.queued;
  },
  
  clickCitySelect : function (city){
    var t = Tabs.Train;
    t.selectedCity = city;
    t.lastQueString = null;   
    t.lastDQueString = null;   
    t.displayCityStats ();
    t.changeTroopSelect();
    t.changeDefSelect();
  },
  
  clickCheckIdlePop : function (){
    var t = Tabs.Train;
    if (document.getElementById ('chkPop').checked)
      Options.maxIdlePop = true;
    else
      Options.maxIdlePop = false;
    saveOptions ();
    t.displayCityStats ();
    t.changeTroopSelect ();
  },
  limitingFactor : null,
  changeTroopSelect : function (){
    var t = Tabs.Train;
    var cityId = t.selectedCity.id;
    var id = t.TTselType.value;
    t.lastTroopSelect = id;
    t.limitingFactor = null;
    var uc = unsafeWindow.unitcost['unt'+id];
    var a=1
    var gumble= t.BOGamble.value;
    if (gumble==0) a=1;
    if (gumble==1) a=2;
    if (gumble==2) a=4;
    var max = 9999999999;
    if ( (t.stats.food / (uc[1]*a)) < max){
      max = t.stats.food / (uc[1]*a);
      t.limitingFactor = 'food';
    }
    if ( (t.stats.wood / (uc[2]*a)) < max){
      max = t.stats.wood / (uc[2]*a);
      t.limitingFactor = 'wood';
    }
    if ( (t.stats.stone / (uc[3]*a)) < max){
      max = t.stats.stone / (uc[3]*a);
      t.limitingFactor = 'stone';
    }
    if ( (t.stats.ore / (uc[4]*a)) < max){
      max = t.stats.ore / (uc[4]*a);
      t.limitingFactor = 'ore';
    }
    if ( (t.stats.idlePop / uc[6]) < max){
      max = t.stats.idlePop / (uc[6]);
      t.limitingFactor = 'pop';
    }   
    t.stats.MaxTrain = parseInt (max);
    if (t.stats.MaxTrain < 0)
      t.stats.MaxTrain = 0;
    if (matTypeof(uc[8]) == 'object'){
      for (k in uc[8]){
        var b = getCityBuilding (cityId, k.substr(1));
        if (b.maxLevel < uc[8][k][1]){
          t.stats.MaxTrain = 0;
          t.limitingFactor = null;
          break;
        }
      }
    }
    if (matTypeof(uc[9]) == 'object'){
      for (k in uc[9]){
        if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
          t.stats.MaxTrain = 0;
          t.limitingFactor = null;
          break;
        }
      }
    }
    t.updateTopTroops();
  },

  clickTroopDo : function (){
    var t = Tabs.Train;
    var cityId = t.selectedCity.id;
    unsafeWindow.citysel_click(ById('citysel_'+ (t.selectedCity.idx+1)+''));
    var unitId = t.TTselType.value;
    var perSlot = parseInt(t.TTinpPerSlot.value, 10);
    var numSlots = parseInt(t.TTinpSlots.value, 10);
    
    t.displayCityStats ();
    if (perSlot<1){
      t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>Nombre de troupes par slot incorrect (doit etre > 0)</font>';
      return;
    }
    if (perSlot*numSlots > t.stats.MaxTrain){
      t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>Impossible de former autant de troupes ! (le max est de '+ t.stats.MaxTrain +')</font>';
      return;
    }
    if (numSlots<1 || numSlots>t.stats.barracks - t.stats.queued){
      t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>Nombre incorrect de slots.</font>';
      return;
    }
    
    var tut = document.getElementById ('tutelage').value;
    var gam = t.BOGamble.value;
    t.setBusy(true);
    var que = [];
    for (var i=0; i<numSlots; i++)
      que.push (['T', unitId, parseInt (perSlot)]);
    t.divTrainStatus.innerHTML = '';
    t.doQueue (cityId, tut, gam, que);
  },

  
/*******  DEF  ******/  
  
  updateTopDef : function (){
    var t = Tabs.Train;
    var slots = parseInt(t.TDinpSlots.value, 10);
    if (isNaN(slots) || slots<0)
      slots = 0;
    t.TDspMax.innerHTML = 'max:'+ t.stats.MaxDefTrain +'&nbsp; actuel:'+ t.stats.defOwned;   
    t.TDspMaxSlots.innerHTML = t.stats.wallLevel-t.stats.Dqueued;
    if (slots<1)
      t.TDspMaxPS.innerHTML = 0;
    else
      t.TDspMaxPS.innerHTML = parseInt(t.stats.MaxDefTrain / slots);

    t.TDspSpace.innerHTML = '<table border=1 cellspacing=0 width=100% bordercolor=black><tr><td>Niveau</td><td>D&eacute;fense des Remparts</td><td>D&eacute;fense des Champs</td></tr>\
       <tr><td><B>'+ t.stats.wallLevel +'</b></td><td>'+ (t.stats.wallSpaceUsed+t.stats.wallSpaceQueued)  +'/<B>'+ t.stats.wallSpace +'</b></td>\
        <td>'+ (t.stats.fieldSpaceUsed+t.stats.fieldSpaceQueued) +'/<B>'+ t.stats.fieldSpace +'</b></td></table>';
  },

  changeDefSelect : function (){
    var t = Tabs.Train;
    var cityId = t.selectedCity.id;
    var id = t.TDselType.value;
    t.lastDefSelect = id;
    t.stats.defOwned = parseInt(Seed.fortifications['city' + cityId]['fort'+id]);    
    var uc = unsafeWindow.fortcost['frt'+id];
    var max = 9999999999;
    if ( (t.stats.food / uc[1]) < max)
      max = t.stats.food / uc[1];
    if ( (t.stats.wood / uc[2]) < max)
      max = t.stats.wood / uc[2];
    if ( (t.stats.stone / uc[3]) < max)
      max = t.stats.stone / uc[3];
    if ( (t.stats.ore / uc[4]) < max)
      max = t.stats.ore / uc[4];
    if ( (t.stats.idlePop / uc[6]) < max)
      max = t.stats.idlePop / uc[6];
    t.stats.MaxDefTrain = parseInt (max);
    if (t.stats.MaxDefTrain < 0)
      t.stats.MaxDefTrain = 0;
    if (matTypeof(uc[8]) == 'object'){
      for (k in uc[8]){ 
        var b = getCityBuilding (cityId, k.substr(1));
        if (b.maxLevel < uc[8][k][1]){
          t.stats.MaxDefTrain = 0;
          break;
        }
      }
    }
    if (matTypeof(uc[9]) == 'object'){
      for (k in uc[9]){
        if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
          t.stats.MaxDefTrain = 0;
          break;
        }
      }
    }

    var spaceEach = parseInt(unsafeWindow.fortstats["unt"+ id][5]);
    if (id<60)
      var spaceAvail = t.stats.wallSpace - t.stats.wallSpaceUsed - t.stats.wallSpaceQueued;
    else
      var spaceAvail = t.stats.fieldSpace - t.stats.fieldSpaceUsed - t.stats.fieldSpaceQueued;
    if ( t.stats.MaxDefTrain * spaceEach > spaceAvail)
      t.stats.MaxDefTrain = parseInt(spaceAvail / spaceEach);
    
    t.updateTopDef();
  },
  
  clickDefMaxPS : function (){
    var t = Tabs.Train;
    var slots = parseInt(t.TDinpSlots.value, 10);
    if (slots<1)
      t.TDinpPerSlot.value = 0;
    else
      t.TDinpPerSlot.value = parseInt(t.stats.MaxDefTrain / slots);
  },

  clickDefMaxSlots : function (){
    var t = Tabs.Train;
    t.TDinpSlots.value = t.stats.wallLevel-t.stats.Dqueued;
  },
    
  clickDefDo : function (){
    var t = Tabs.Train;
    var cityId = t.selectedCity.id;
    var unitId = t.TDselType.value;
    var perSlot = parseInt(t.TDinpPerSlot.value, 10);
    var numSlots = parseInt(t.TDinpSlots.value, 10);
    
    t.displayCityStats ();
    if (perSlot<1){
      t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>Le nombre d\'unit&eacute; par slot doit &ecirc;tre au dessus de 0.</font>';
      return;
    }
    if (perSlot*numSlots > t.stats.MaxDefTrain){
      t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>Impossible de former, trop d\'unit&eacute; (le max est de '+ t.stats.MaxDefTrain +')</font>';
      return;
    }
    if (numSlots<1 || numSlots > t.stats.wallLevel-t.stats.Dqueued){
      t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>Nombre de slots incorrecte.</font>';
      return;
    }
    var siege = document.getElementById ('siege').value;
    t.setBusy(true);
    var que = [];
    for (var i=0; i<numSlots; i++)
      que.push (['T', unitId, parseInt (perSlot)]);
    t.divTrainStatus.innerHTML = '';
    t.doDefQueue (cityId, siege, que);
  },

  doDefQueue : function (cityId, siege, que, errMsg){
    var t = Tabs.Train;
    try {
      t.displayCityStats();
      if (errMsg){
        t.dispTrainStatus ('<font color=#550000><B>ERREUR : '+ errMsg +'</b></font><BR>');
        t.setBusy(false);
        return;
      }
      var cmd = que.shift();
      if (!cmd){
        t.dispTrainStatus ('<B>File d\'attente d&eacute;fenses termin&eacute;e.</b><BR>');
        t.setBusy(false);
        return;
      }
      if (cmd[0] == 'T'){
        t.dispTrainStatus ('Construction '+ cmd[2] +' '+  fortNamesShort[cmd[1]] +'<BR>');
          doDefTrain ( cityId, siege, cmd[1], cmd[2], 
          function(errMsg){
            setTimeout(function (){Tabs.Train.doDefQueue(cityId, siege, que, errMsg);}, (Math.random()*3500)+500);
          } );
      }
    } catch (err) {
      t.dispTrainStatus ('<font color=#550000>PROGRAMME ERREUR : '+ err.message +'</font><BR>');
      t.setBusy(false);
    }
  },
  setBusy : function (tf){
    var t = Tabs.Train;
    t.TDbutDo.disabled = tf;
    t.TTbutDo.disabled = tf;
  },
  fixQueTimes : function (q){
    var now = unixTime();
    if (q[0][2] > now)
      q[0][2] = now;
    for (var i=0; i<q.length; i++){
      if (q[i+1]!=null && q[i+1][2]!=q[i][3])
        q[i][3] = q[i+1][2];
    }        
  }, 
  displayCityStats : function (){
    var t = Tabs.Train;
    var cityId = t.selectedCity.id;
    t.stats.food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
    t.stats.wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
    t.stats.stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
    t.stats.ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
    t.stats.gold = Seed.citystats['city'+cityId].gold[0];
    if (Options.maxIdlePop)
       t.stats.idlePop = parseInt(Seed.citystats['city'+cityId].pop[0]);
     else
       t.stats.idlePop = parseInt(Seed.citystats['city'+cityId].pop[0]) - parseInt(Seed.citystats['city'+cityId].pop[3]);
    t.stats.barracks = getCityBuilding (cityId, 13).count;
    cost = unsafeWindow.unitcost['unt'+t.TTselType.value];
    nbunit=t.TTinpPerSlot.value*t.TTinpSlots.value;
    var a=1;
    var gumble= t.BOGamble.value;
    if (gumble==0) a=1;
	    if (gumble==1) a=2;
	    if (gumble==2) a=4;
         consoFood = cost[1] * a * nbunit;
        styleFood="";stylePop="";styleWood="";styleOre="";styleStone="";
        if (consoFood>t.stats.food) styleFood='style="color:#E30;font-weight:bold;"';
        consoOre = cost[4] * a * nbunit;
        if (consoOre>t.stats.ore) styleOre='style="color:#E30;font-weight:bold;"';
        consoStone = cost[3] * a * nbunit;
        if (consoStone>t.stats.stone) styleStone='style="color:#E30;font-weight:bold;"';
        consoWood = cost[2] * a * nbunit;
        if (consoWood>t.stats.wood) styleWood='style="color:#E30;font-weight:bold;"';
        consoPop = cost[6] * nbunit;
    if (consoPop>t.stats.idlePop) stylePop='style="color:#E30;font-weight:bold;"';
    
    var m = '<TABLE class=ptTab width=100%><TR align=center>\
        <TD width=8%><B>Ravi:</b></td><TD width=8%><B>Mili:</b></td><TD width=8%><B>Ecla:</b></td>\
        <TD width=8%><B>Piqu:</b></td><TD width=8%><B>Pala:</b></td><TD width=8%><B>Arch:</b></td>\
        <TD width=8%><B>Cav:</b></td><TD width=8%><B>CavL:</b></td><TD width=8%><B>Wago:</b></td>\
        <TD width=8%><B>Bali:</b></td><TD width=8%><B>Beli:</b></td><TD width=8%><B>Cata:</b></td><tr>';
		
 m += '<TR align=center><TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(1,'+cityId+');">'+Seed.units['city'+cityId]['unt1']+'</span></td><TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(2,'+cityId+');">'+Seed.units['city'+cityId]['unt2']+
 '<TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(3,'+cityId+');">'+Seed.units['city'+cityId]['unt3']+'</td><TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(4,'+cityId+');">'+Seed.units['city'+cityId]['unt4']+
 '<TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(5,'+cityId+');">'+Seed.units['city'+cityId]['unt5']+'</td><TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(6,'+cityId+');">'+Seed.units['city'+cityId]['unt6']+
 '<TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(7,'+cityId+');">'+Seed.units['city'+cityId]['unt7']+'</td><TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(8,'+cityId+');">'+Seed.units['city'+cityId]['unt8']+
 '<TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(9,'+cityId+');">'+Seed.units['city'+cityId]['unt9']+'</td><TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(10,'+cityId+');">'+Seed.units['city'+cityId]['unt10']+
 '<TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(11,'+cityId+');">'+Seed.units['city'+cityId]['unt11']+'</td><TD width=8%><span title="'+unsafeWindow.g_js_strings.commonstr.dismiss+'" onclick="BoRenvoyer(12,'+cityId+');">'+Seed.units['city'+cityId]['unt12']+'</td><tr></table>';
   
 m += '<TABLE class=ptTab width=100%><TR align=center>\
        <td width=15%>&nbsp;</td><TD width=14%><B>'+unsafeWindow.g_js_strings.commonstr.gold+'</b></td><TD width=15%><B>'+unsafeWindow.g_js_strings.commonstr.food+'</b></td><TD width=14%><B>'+unsafeWindow.g_js_strings.commonstr.wood+'</b></td><TD width=14%><B>'+unsafeWindow.g_js_strings.commonstr.stone+'</b></td><TD width=14%><B>'+unsafeWindow.g_js_strings.commonstr.ore+'</b></td><TD width=14%><B>'+unsafeWindow.g_js_strings.showPopTooltip.idlepop+'</b></td></tr>\
      <TR align=center><td><b>'+uW.g_js_strings.commonstr.inventory+'</b></td><TD><SPAN id=ptttr_gold>'+ addCommasInt(t.stats.gold) +'</span></td><TD><SPAN id=ptttr_food>'+ addCommasInt(t.stats.food) +'</span></td>\
      <TD><SPAN id=ptttr_wood>'+ addCommasInt(t.stats.wood) +'</span></td><TD><SPAN id=ptttr_stone>'+ addCommasInt(t.stats.stone) +'</span></td><TD><SPAN id=ptttr_ore>'+ addCommasInt(t.stats.ore) +'</span></td>\
         <TD><SPAN id=ptttr_gold>'+ addCommasInt(t.stats.idlePop) +'</span></td></tr>\
        <tr align=center><td width=15%><b>'+unsafeWindow.g_js_strings.commonstr.required+'</b></td><td>&nbsp;</td><td '+styleFood+'>'+addCommasInt(consoFood)+'</td><td '+styleWood+'>'+addCommasInt(consoWood)+'</td><td '+styleStone+'>'+addCommasInt(consoStone)+'</td><td '+styleOre+'>'+addCommasInt(consoOre)+'</td>\
        <TD '+stylePop+'>'+ addCommasInt(consoPop)+'</td></tr>\
       </table>';  
       document.getElementById ('divSTtop').innerHTML = m;  
       var e=parseInt((t.TDinpPerSlot.value*t.TDinpSlots.value),10);
       if (e>0) {
          d=t.TDselType.value;
          var a=unsafeWindow.modal_walls_traintime(d,e)
          
          var reduction=0
          var tut = ById('siege').value;   
          if (tut==26) reduction=parseInt(a*0.3);
           
          var reducStr=timestr(reduction,1);
          ById('BOmodal_barracks_deftime').innerHTML=uW.g_js_strings.modal_barracks_trainingtab.esttime+" : <b>" + timestr(a,1) +"</b>";
          if (reduction>0) {
           var totalred = a - reduction;
           ById('BOmodal_barracks_deftime').innerHTML=uW.g_js_strings.modal_barracks_trainingtab.esttime+" : <b>" + timestr(totalred,1) +"</b>";
           ById('BOmodal_barracks_deftime').title=uW.g_js_strings.modal_barracks_trainingtab.esttime+" : " + timestr(a,1) +" - Reduction : " + reducStr + "";
          }
         }
    var e=parseInt(nbunit,10);
    var b=t.TTselType.value;
    var m=0;

    if(e>0){
     var m=parseInt(parseInt(unsafeWindow.unitcost["unt"+b][7]))*e;
     var c=0;
     var d=0;
     var h=0;
     var j=Object.keys(Seed.buildings["city"+cityId]);
     for(var f=0;f<j.length;f++){
      var k=Seed.buildings["city"+cityId][j[f]];
      if((parseInt(k[0])==13)&&(parseInt(k[1])>0)){
       c+=(parseInt(k[1])+9)
      }
      if((parseInt(k[0])==16)&&(parseInt(k[1])>d)){
       if(parseInt(b)>=9){
        d=parseInt(k[1])
       }
      }
      if((parseInt(k[0])==17)&&(parseInt(k[1])>h)){
       if(parseInt(b)>=7){
        h=parseInt(k[1])
       }
      }
     }
     var a=c/10;
     var l=0;
     var g=0;
     var n=Seed.knights["city"+cityId];
     m=Math.max(1,Math.ceil(m/a));
     a=1;
     l=d+h;
     if(n){
      n=n["knt"+Seed.leaders["city"+cityId].combatKnightId];
      if(n){
       g=parseInt(n.combat);
       newkntlv=((parseInt(n.combatBoostExpireUnixtime)-unixTime())>0)?(g*1.25):g;
       a=a+(0.005*newkntlv)
      }
     }
     if(Seed.tech){
      l=l+Seed.tech.tch5;
     }
     a=a+(0.1*l);
     m=Math.max(1,Math.ceil(m/a));
     var h=uW.cm.ThroneController.effectBonus(77);
     m=m/(1+(h/100));
     var reduction=0
     var tut = document.getElementById ('tutelage').value;   
     if (tut==36)
       reduction=parseInt(m*0.3,10);
     if (tut==37)
      reduction=parseInt(m*0.5,10);
     if (tut==38)
      reduction=parseInt(m*0.7,10);

     var reducStr=timestr(reduction,1);
      
     var aa=1;
     var now = unixTime();
     var estimfin = new Date();
     estimfin.setTime((now+m) * 1000);
     ById('BOmodal_barracks_traintime').innerHTML=uW.g_js_strings.modal_barracks_trainingtab.esttime+" : <b>" + timestr(m,1) +"</b><br>Heure de fin : "+estimfin.toLocaleString()+"";
     var gumble= t.BOGamble.value;
     if (gumble==0) aa=1;
     if (gumble==1) aa=2;
     if (gumble==2) aa=4;
     if (aa>1 && reduction==0) {
      if (aa==2) {
       var r1=parseInt(m*0.05,10);
       var r2=parseInt(m*0.15,10);
       var n1 = m - r1;
       var n2 = m - r2;
      }
      if (aa==4) {
       var r1=parseInt(m*0.10,10);
       var r2=parseInt(m*0.25,10);
       var n1 = m - r1;
       var n2 = m - r2;
      }
      var now = unixTime();
      var estimfin1 = new Date();
      estimfin1.setTime((now+n2) * 1000);
      var estimfin2 = new Date();
      estimfin2.setTime((now+n1) * 1000);
      ById('BOmodal_barracks_traintime').innerHTML=uW.g_js_strings.modal_barracks_trainingtab.esttime+" <b><font color=red>" + timestr(n2,1) +"</font> et <font color=red>" + timestr(n1,1) +"</font></b><br>Heure de fin entre "+estimfin1.toLocaleString()+"<br>et "+estimfin2.toLocaleString()+"";     
     }
     if (reduction>0 && aa==1) {
       var totalred = m - reduction;
       var now = unixTime();
       var estimfin = new Date();
       estimfin.setTime((now+totalred) * 1000);
       ById('BOmodal_barracks_traintime').innerHTML=uW.g_js_strings.modal_barracks_trainingtab.esttime+" : <b><font color=red>" + timestr(totalred,1) +"</font></b><br>Heure de fin : "+estimfin.toLocaleString()+"";
       ById('BOmodal_barracks_traintime').title=uW.g_js_strings.modal_barracks_trainingtab.esttime+" : " + timestr(m,1) +" - Reduction : " + reducStr + "";
     }
     if (reduction>0 && aa>1) {
            var totalred = m - reduction;           
             if (aa==2) {
	           var r1=parseInt(totalred*0.05,10);
	           var r2=parseInt(totalred*0.15,10);
	           var n1 = totalred - r1;
	           var n2 = totalred - r2;
	          }
	          if (aa==4) {
	           var r1=parseInt(totalred*0.10,10);
	           var r2=parseInt(totalred*0.25,10);
	           var n1 = totalred - r1;
	           var n2 = totalred - r2;
	          }
	          
	          var now = unixTime();
		        var estimfin1 = new Date();
		        estimfin1.setTime((now+n2) * 1000);
		        var estimfin2 = new Date();
      estimfin2.setTime((now+n1) * 1000);
 ById('BOmodal_barracks_traintime').innerHTML=uW.g_js_strings.modal_barracks_trainingtab.esttime+" <b><font color=red>" + timestr(n2,1) +"</font> et <font color=red>" + timestr(n1,1) +"</font></b><br>Heure de fin entre "+estimfin1.toLocaleString()+"<br>et "+estimfin2.toLocaleString()+"";
     }
    }
    var totTime = 0;
    var q = Seed.queue_unt['city'+cityId];
    var c = Cities.byID[cityId].idx;
    t.stats.queued = q.length;
    var qs = q.toString();
    var now = unixTime();
    if (q!=null && q.length>0)
      totTime = q[q.length-1][3] - now;
    if ( qs == t.lastQueString){
      if (q!=null && q.length>0){
        var cur = q[0][3] - now;
        if (cur < 1)
          q.shift(); 
        if (document.getElementById ('ptttfq')) document.getElementById ('ptttfq').innerHTML = timestr(cur, true);
      }
    } else {
      t.lastQueString = qs;
      t.stats.queued = 0;
      m = '<TABLE align=center class=ptTab>';
      if (q!=null && q.length>0 ){
        t.fixQueTimes (q);
        t.stats.queued = q.length;
        first = true;
        for (var i=0; i<q.length; i++){
          start = q[i][2];
          end = q[i][3];
          if (first)
            actual = end - now;
          else
            actual = end - lastEnd;
          if (actual < 0)
            actual = 0;
            param1=i; // 
            param2=cityId; // id de la ville
            param3=q[i][0]; // Type de trouoe
            param4=q[i][1]; // Qte troupe
            param5=end; // debut
            param6=start; // fin
            param7=actual; // duree
          m += '<TR align=right><td width=35 align=center>'+(i+1)+'&nbsp;<a onclick="BOcancelTraining('+param1+','+param2+','+param3+','+param4+','+param5+','+param6+','+param7+');return false;" href="javascript:void(0);"><img src="http://cdn1.iconfinder.com/data/icons/musthave/16/Remove.png" border=0 title="Annuler la formation"></a></td><TD>'+ q[i][1] +' </td><TD align=left> '+ unsafeWindow.unitcost['unt'+q[i][0]][0].replace('de Ravitaillement','');
          if (first)
            m += '</td><TD>&nbsp;<img src="http://cdn1.iconfinder.com/data/icons/ledicons/wait.png" onclick=citysel_click(document.getElementById(\'citysel_'+ (c+1)+'\'));modal_speedup("trn",'+param3+','+param3+',"Training",'+param6+');return false;> &nbsp; '+  timestr(end-start, true) +'</td><TD> (<SPAN id=ptttfq>'+ timestr(actual, true) +'</span>)';
          else
            m += '</td><TD> &nbsp; '+  timestr(actual, true) +'</td></tr>'; 
          lastEnd = end;
          first = false;
         }
      }
      m += '</table>';
      document.getElementById ('divSTleft').innerHTML = m;
    }
    m = t.stats.barracks +' casernes';
    if (t.stats.queued > 0)
      m += ', '+ t.stats.queued +' slots';
    if (totTime > 0)
      m += ', '+ unsafeWindow.timestr(totTime);
    document.getElementById ('statTTtot').innerHTML = m;
    getWallInfo (cityId, t.stats);    
    var totTime = 0;
    var q = Seed.queue_fort['city'+cityId];
    var qs = q.toString();
    if (q!=null && q.length>0)
      totTime = q[q.length-1][3] - now;
    if ( qs == t.lastDQueString){
      if (q!=null && q.length>0){
        var cur = q[0][3] - now;
        if (cur < 1)
          q.shift(); 
        document.getElementById ('pttdfq').innerHTML = timestr(cur, true);
      }
    } else {
      t.lastDQueString = qs;
      t.stats.Dqueued = 0;
      t.stats.wallSpaceQueued = 0;
      t.stats.fieldSpaceQueued = 0;
      m = '<TABLE align=center class=ptTab>';
      if (q!=null && q.length > 0 ){
        t.fixQueTimes (q);
        t.stats.Dqueued = q.length;
        first = true;
        for (i=0; i<q.length; i++){
          if (q[i][0] < 60)          
            t.stats.wallSpaceQueued += parseInt(unsafeWindow.fortstats["unt"+ q[i][0]][5]) * parseInt(q[i][1]);
          else          
            t.stats.fieldSpaceQueued += parseInt(unsafeWindow.fortstats["unt"+ q[i][0]][5]) * parseInt(q[i][1]);
          start = q[i][2];
          end = q[i][3];
          if (first)
            actual = end - now;
          else
            actual = end - lastEnd;
          if (actual < 0)
            actual = 0;
          q[i][7]=cityId;
          m += '<TR align=right><TD><a onclick="BOcancelFort('+ q[i][0]+','+q[i][1]+','+q[i][2]+','+q[i][3]+','+q[i][5]+','+q[i][6]+','+q[i][7] +','+ i +');return false;" href="javascript:void(0);"><img src="http://cdn1.iconfinder.com/data/icons/musthave/16/Remove.png" border=0 title="Annuler la fortification"></a></td><TD>'+ q[i][1] +'</td><TD align=left> '+ fortNamesShort[q[i][0]];
          if (first)
            m += '</td><TD> &nbsp; '+  timestr(end-start, true) +'</td><TD> (<SPAN id=pttdfq>'+ timestr(actual, true) +'</span>)';
          else
            m += '</td><TD> &nbsp; '+  timestr(actual, true) +'</td></tr>'; 
          lastEnd = end;
          first = false;
        }
      }
      m += '</table>';
      document.getElementById ('divSTright').innerHTML = m;
    }
    m = t.stats.Dqueued +' slots';
    if (totTime > 0)
      m += ', '+ unsafeWindow.timestr(totTime);
    document.getElementById ('statDTtot').innerHTML = m;
  },
  dispTrainStatus : function (msg){
    var t = Tabs.Train;
    t.divTrainStatus.innerHTML = msg + t.divTrainStatus.innerHTML;
  }, 
  CancelActionall: function(cityId, num, fintraitement) {
   var t = Tabs.Train;
   var q = Seed.queue_unt['city'+cityId];
   var now = unixTime();
   start = q[num][2];
   end = q[num][3];
   if (first)
         actual = end - now;
      else
          actual = end - lastEnd;
   if (actual < 0)
          actual = 0;
   var param2=cityId; // id de la ville
   var param3=q[num][0]; // Type de trouoe
   var param4=q[num][1]; // Qte troupe
   var param5=end; // debut
   var param6=start; // fin
   var param7=actual; // duree
   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
   params.cityId = param2;
   params.requestType ="CANCEL_TRAINING";
   params.numtrptrn = param4;
   params.trnETA= param5;
   params.trnNeeded = param7;
   params.trnTmp = param6;
   params.typetrn= param3;
   new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelTraining.php" + unsafeWindow.g_ajaxsuffix, {
             method: "post",
             parameters: params,
           onSuccess: function (rslt) {
            var t = Tabs.Train;
            if (rslt.ok) {
               unsafeWindow.update_seed_ajax(true,function(){
   	       var k=0;for(var j=0;j<unsafeWindow.seed.queue_unt["city"+param2].length;j++){
   	        if(j>num){
   	         unsafeWindow.seed.queue_unt["city"+param2][j][2]=parseInt(rslt.dateTraining[k]["start"]);
   	         unsafeWindow.seed.queue_unt["city"+param2][j][3]=parseInt(rslt.dateTraining[k]["end"]);
   	         k++;
   	         }
   	        }
   	        unsafeWindow.seed.queue_unt["city"+param2].splice(num,1);
   	        for(var i=1;i<5;i++){
   	         var totalReturn=parseInt(unsafeWindow.unitcost["unt"+param3][i])*parseInt(param4)*3600/2;
   	         unsafeWindow.seed.resources["city"+param2]["rec"+i][0]=parseInt(unsafeWindow.seed.resources["city"+param2]["rec"+i][0])+totalReturn;
   	        }
   
       	       });
	        var numnew = num - 1;
	        if (numnew<fintraitement) {
	         t.dispTrainStatus ('<font color=#550000><B>Annulation des formations r&eacute;ussie</b></font><BR>');
                 document.getElementById ('BOCancelAllTrain').style.display='block';
	         t.displayCityStats();
	        } else {
	          setTimeout(function (){
	            t.CancelActionall(cityId, numnew, fintraitement);
		  }, (Math.random()*200)+150);
                }
             
            } else {
             t.dispTrainStatus ("<font color=#550000><B>ERREUR : Impossible d'annuler les formations...<br>Actualisez le jeu et recommencer.</b></font><BR>");
             t.displayCityStats();
             document.getElementById ('BOCancelAllTrain').style.display='block';
            }
           },
           onFailure: function (rslt) {
            var t = Tabs.Train;
            t.dispTrainStatus ("<font color=#550000><B>ERREUR : Impossible d'annuler les formations...<br>Actualisez le jeu et recommencer.</b></font><BR>");
            t.displayCityStats();
            document.getElementById ('BOCancelAllTrain').style.display='block';
           }
    });
  }, 
  CancelAllTraining : function() {
   var t = Tabs.Train;
   var cityId = t.selectedCity.id;
   var q = Seed.queue_unt['city'+cityId];
   if (q.length>0) {
    var b=prompt("A partir de quel slot voulez-vous annuler ? (1=formation en cours a "+(q.length)+")", 2);
    if (parseInt(b)<=q.length && parseInt(b)>0) {
     t.dispTrainStatus ('<font color=#550000><B>Annulation des formation en cours... MERCI DE PATIENTER !</b></font><BR>');
     document.getElementById ('BOCancelAllTrain').style.display='none';
     obj = ById('autoFormationtoggle');
     TrainOptions.Running = false;
     if (obj) obj.value = "FormationAUTO = OFF";
     updatebotbutton('Form - OFF', 'pbformtab');
     saveTrainingOptions();
     t.CancelActionall(cityId, q.length-1, b-1);
    } 
   }
  },
  cancelTrainingBO : function (p1,p2,p3,p4,p5,p6,p7) {
   var t = Tabs.Train;
   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
     params.cityId = p2;
     params.requestType ="CANCEL_TRAINING";
     params.numtrptrn = p4;
     params.trnETA= p5;
     params.trnNeeded = p7;
     params.trnTmp = p6;
     params.typetrn= p3
 
  new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelTraining.php" + unsafeWindow.g_ajaxsuffix, {
          method: "post",
          parameters: params,
        onSuccess: function (rslt) {
         var t = Tabs.Train;
         if (rslt.ok) {
              unsafeWindow.update_seed_ajax(true,function(){
	       var k=0;for(var j=0;j<unsafeWindow.seed.queue_unt["city"+p2].length;j++){
	        if(j>p1){
	         unsafeWindow.seed.queue_unt["city"+p2][j][2]=parseInt(rslt.dateTraining[k]["start"]);
	         unsafeWindow.seed.queue_unt["city"+p2][j][3]=parseInt(rslt.dateTraining[k]["end"]);
	         k++;
	         }
	        }
	        unsafeWindow.seed.queue_unt["city"+p2].splice(p1,1);
	        for(var i=1;i<5;i++){
	         var totalReturn=parseInt(unsafeWindow.unitcost["unt"+p3][i])*parseInt(p4)*3600/2;
	         unsafeWindow.seed.resources["city"+p2]["rec"+i][0]=parseInt(unsafeWindow.seed.resources["city"+p2]["rec"+i][0])+totalReturn;
	        }
    	       });
          t.dispTrainStatus ('<font color=#550000><B>Annulation de la formation r&eacute;ussie</b></font><BR>');
          t.displayCityStats();
         } else {
          t.dispTrainStatus ("<font color=#550000><B>ERREUR : Impossible d'annuler la formation...</b></font><BR>");
          t.displayCityStats();
         }
        },
        onFailure: function (rslt) {
         var t = Tabs.Train;
         t.dispTrainStatus ("<font color=#550000><B>ERREUR : Impossible d'annuler la formation...</b></font><BR>");
         t.displayCityStats();
        }
    });
  },
 butcancelFort : function (typefrt, numtrpfrt, frtTmp, frtETA, frtNeeded, frtid, cityId, queueId){
   var t = Tabs.Train;
   var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams); 
   params.pf =0;
   params.requestType = "CANCEL_FORTIFICATIONS";
   params.cityId = cityId;
   params.typefrt = typefrt;
   params.numtrpfrt =  numtrpfrt;
   params.frtETA = frtETA;
   params.frtTmp = frtTmp;
   params.frtNeeded = frtNeeded;
   params.frtid = frtid;  
   new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelFortifications.php" + unsafeWindow.g_ajaxsuffix, {
       method: "post",
       parameters: params,
       onSuccess: function (message) {
       var rslt=eval("("+message.responseText+")");
       var t = Tabs.Train;
       if (rslt.ok) {
 			var k=0;
 			for(var j=0;j<Seed.queue_fort["city"+cityId].length;j++){
 				if(j>queueId){
 					Seed.queue_fort["city"+cityId][j][2]=parseInt(rslt.dateFortifications[k]["start"]);
 					Seed.queue_fort["city"+cityId][j][3]=parseInt(rslt.dateFortifications[k]["end"]);
 					k++;
 				}
 			}
			unsafeWindow.update_seed(rslt.updateSeed);
 			Seed.queue_fort["city"+cityId].splice(queueId,1);
 			for(var i=1;i<5;i++){
 				var totalReturn=parseInt(unsafeWindow.fortcost["frt"+typefrt][i])*parseInt(numtrpfrt)*3600/2;
 				Seed.resources["city"+cityId]["rec"+i][0]=parseInt(Seed.resources["city"+cityId]["rec"+i][0])+totalReturn;
 			}
 		  t.dispTrainStatus ('<font color=#550000><B>Annulation de la fortification r&eacute;ussie</b></font><BR>');
         	  t.displayCityStats();	
 		} else {
 		  
		  t.dispTrainStatus ("<font color=#550000><B>ERREUR : Impossible d'annuler la fortification...</b></font><BR>");
                  t.displayCityStats();
 		}
 		
       },
       onFailure: function () {
       var t = Tabs.Train;
       		  t.dispTrainStatus ("<font color=#550000><B>ERREUR : Impossible d'annuler la fortification...</b></font><BR>");
                  t.displayCityStats();
       },
   });
 },
  doQueue : function (cityId, tut, gam, que, errMsg){
    var t = Tabs.Train;
    try {
      t.displayCityStats();
      if (errMsg){
        t.dispTrainStatus ('<font color=#550000><B>ERREUR : '+ errMsg +'</b></font><BR>');
        t.setBusy(false);
        return;
      }
      var cmd = que.shift();
      if (!cmd){
        t.dispTrainStatus ('<B>File d\'attente des troupes termin&eacute;e.</b><BR>');
        t.setBusy(false);
        return;
      }
      if (cmd[0] == 'T'){
        t.dispTrainStatus ('Formation '+ cmd[2] +' '+  unsafeWindow.unitcost['unt'+cmd[1]][0] +' dans '+ Cities.byID[cityId].name +' ('+ que.length +' slot(s) restant(s))<BR>');
        doTrain (cityId, tut, gam, cmd[1], cmd[2], 
          function(errMsg){
	           setTimeout(function (){Tabs.Train.doQueue(cityId, tut, gam, que, errMsg);}, (Math.random()*1000)+1000 );
          }
        );
      }
    } catch (err) {
      t.dispTrainStatus ('<font color=#550000>PROGRAME ERREUR : '+ err.message +'</font><BR>');
      t.setBusy(false);
    }
  },
}


/*************** WILDS TAB *********************/
var wildNames={0:"Marais",10:"Prairie",11:"Lac",20:"Bois",30:"Collines",40:"Montagne",50:"Plaine"};var mercNames={0:"Aucun",1:"Novices",2:"Intermediaire",3:"Veterans"}
Tabs.Wilds = {
  tabOrder : 9,
  tabLabel: 'Terres',
  cont : null,
  state : null,
  upGoldTimer : null,
  wildList : [],
  buildList : {},
  
  show : function (){
  },

  hide : function (){
    var t = Tabs.Wilds;
    clearTimeout (t.upGoldTimer);
  },
  
  init : function (div){
    var t = Tabs.Wilds;
   
    unsafeWindow.ptButMaxTraps = t.e_butMaxTraps;
    unsafeWindow.ptInpWildTraps = t.e_inpTraps;
    unsafeWindow.ptButWildSet = t.e_butWildSet;
    unsafeWindow.ptButWildShow = t.init;
    clearTimeout (t.upGoldTimer);
    if (t.state == null){
      t.cont = div;
      t.cont.innerHTML = '<DIV id=wildContent style="maxheight:'+(Options.HauteurBoite-25)+'px; height:'+(Options.HauteurBoite-25)+'px; overflow-y:auto">';
      t.state = 1;
    }
    
    m = '<TABLE cellspacing=0 cellpadding=0 class=ptTabPad align=center width=99%>';
    for (var c=0; c<Cities.numCities; c++){
      var city = Cities.cities[c];
      t.wildList[c] = [];    
      
      var totWilds = 0;
      var datw = Seed.wilderness['city'+ city.id];
      if (datw!=null && matTypeof(datw)=='object')
       for (k in datw)
        ++totWilds;
      var nivcastle = parseInt(Seed.buildings['city'+ city.id].pos0[1]);
              var castle = nivcastle;
              if (nivcastle==11) castle=12; 
        if (nivcastle==12) castle=14; 
      if (totWilds < castle)  {
        var totWildsstring = '<SPAN style="font-color:red"><B>'+ totWilds +'/'+ castle +'</b></span>';
      }else{
          var totWildsstring = totWilds +'/'+ castle;
      }
      
      
      m += '<TR><TD colspan=21><DIV class=boStat>'+ city.name +' &nbsp; ('+ city.x +','+ city.y +') - '+totWildsstring+'</div></td></tr>';
      var row = 0;  
      var sortem = [];
      
      var cWilds = Seed.wilderness['city'+city.id];
      if (matTypeof(cWilds) != 'array') {
        m += '<TR style="font-weight:bold;" align=right><TD align=left>'+uW.g_js_strings.commonstr.wilderness+'</td><TD></td><TD align=left>Coord</td><td>Dist</td><TD>'+uW.g_js_strings.commonstr.traps+'</td><TD align=left>Merc</td>\
         <TD width=15></td><TD colspan=3 class=entry>'+ htmlTitleLine(' '+uW.g_js_strings.modaltitles.wildernessdefense.toUpperCase()+' ') +'</td></tr>';
        for (var k in Seed.wilderness['city'+city.id])
          sortem.push (Seed.wilderness['city'+city.id][k]);
        sortem.sort (function (a,b){
          var x; if ((x = b.tileLevel-a.tileLevel)!=0) 
            return x; 
          return a.tileType-b.tileType;
        });
        for (i=0; i<sortem.length; i++){
          var wild = sortem[i]; 
          var wildDef = Seed.wildDef['t'+wild.tileId];
          if (wildDef==undefined || !wildDef)
            wildDef = {fort60Count:0, mercLevel:0};
          var maxTraps = parseInt(wild.tileLevel)*100;
          var maxBuild = maxTraps - parseInt(wildDef.fort60Count);
           var distancedelaville = distance (city.x, city.y, wild.xCoord, wild.yCoord);
          t.wildList[c][i] = [wild.tileId, maxBuild];          
          m += '<TR align=right><TD align=left><a onclick="citysel_click(document.getElementById(\'citysel_'+ (c+1)+'\'));setTimeout (function (){modal_wilderness_abandon('+wild.tileId+','+ wild.tileLevel +','+wild.tileType+','+ wild.xCoord +','+ wild.yCoord +');setTimeout(function(){ ptButWildShow(this); },4000);},500);return false;"><img src="http://cdn1.iconfinder.com/data/icons/musthave/16/Remove.png" border=0 title="'+uW.g_js_strings.commonstr.abandon+'"></a>&nbsp;'+ wildNames[wild.tileType] +'</td>\
            <TD>'+ wild.tileLevel +'</td><TD align=center>\
             <a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ wild.xCoord +','+ wild.yCoord +')</a></td><td><b>'+distancedelaville+'</td>\
            <TD align=right><B>'+ wildDef.fort60Count +'</b></td><TD align=center><B>'+ mercNames[wildDef.mercLevel] +'</b></td>\
            <TD></td><TD align=left class=ptentry><B>Ajout Pi&egrave;ges :</b> <INPUT onchange="ptInpWildTraps(this)" id=ptwt_'+ c +'_'+ i 
              + (maxBuild==0?' DISABLED ':'')+' style="margin:0px; padding:0px" type=text size=3 maxlength=4></td>'
          if (wildDef.fort60Count < maxTraps)
            m += '<TD class=ptentry style="padding:0px">'+ strButton14('Max', 'id=ptwx_'+ c +'_'+ i +' onclick="ptButMaxTraps(this)"') +'</td>';
          else
            m += '<TD class=ptentry></td>';
          m += '<TD class=ptentry> &nbsp; &nbsp; <B>Mercs:</b> ' + htmlSelector(mercNames, wildDef.mercLevel, 'id=ptwm_'+ c +'_'+ i) +' &nbsp; &nbsp; </td></tr>';
        }
        m += '<TR><TD colspan=7></td><TD class=ptentry align=center colspan=3><TABLE><TR><TD width=40% align=left>Co&ucirc;t Or : <SPAN id=ptwgc_'+ c +'>0</span></td>\
            <TD width=10%>'+ strButton20(uW.g_js_strings.commonstr.upgrade.toUpperCase(), 'onclick="ptButWildSet('+ c +')"') +'<TD width=40% align=right><SPAN id=ptwgt_'+ c +'></span></td></td></tr></table></td></tr>';
      } else {
        m+= '<TR><TD colspan=10> &nbsp; </td></tr>';
      }         
    }
    ById('wildContent').innerHTML = m + '</table></div>';
    t.updateGold ();
  },
    
  e_butWildSet : function (c){
    var t = Tabs.Wilds;
    var totTraps = 0;  
    var cid = Cities.cities[c].id;
    t.buildList = {cityId:cid, list:[]};
          
    for (var w=0; w<t.wildList[c].length; w++){
      var wild = Seed.wilderness['city'+cid]['t'+t.wildList[c][w][0]]; 
      var wildDef = Seed.wildDef['t'+t.wildList[c][w][0]];
      if (wildDef==undefined || !wildDef)
        wildDef = {fort60Count:0, mercLevel:0};
    
      var numTraps = parseInt(ById('ptwt_'+ c +'_'+ w).value, 10);
      if (isNaN(numTraps))
        numTraps = 0;
      totTraps += numTraps;
      if (numTraps > 0)
        t.buildList.list.push (['T', wild.tileId, numTraps]);
      var mercId=ById('ptwm_'+ c +'_'+ w).value; 
      if (wildDef.mercLevel != mercId)
        t.buildList.list.push (['M', wild.tileId, mercId, wildDef.mercLevel]);
    }

    var totCost = totTraps * 200; 
    if (totCost > parseInt(Seed.citystats['city'+cid].gold[0])){
      ById('ptwgc_'+ c).innerHTML = '<SPAN class=boldRed>'+ addCommasInt(totCost) +'</span>';
      return; 
    }
    if (t.buildList.list.length == 0)
      return;
    t.setCurtain (true);
    var popDiv = t.setPopup (true);
    popDiv.innerHTML = '<TABLE class=ptTab width=100% height=100%><TR><TD>\
          <DIV class=boStat>Configuration des d&eacute;fenses des terres sauvages (TS)</div>\
          <DIV id=ptWildBuildDiv class=ptDiv style="padding:10px; height:225px; max-height:225px; overflow-y:auto"></div>\
          </td></tr><TR><TD align=center>'+ strButton20('ANNULER', 'id=ptWildCancel') +'</td></tr></table>';
    ById('ptWildCancel').addEventListener('click', t.e_buildCancel, false);
    t.processQue(null);  
  },
  
  e_buildCancel : function (){
    var t = Tabs.Wilds;
    t.setCurtain(false);
    t.setPopup(false);
    t.init();
  },
  
  processQue : function (errMsg){
    var t = Tabs.Wilds;
    var what = t.buildList.list.shift();
    var div = ById('ptWildBuildDiv');
    if (what==null || errMsg){
      if (errMsg)
        div.innerHTML += '<BR><SPAN style="white-space:normal;" class=boldRed>ERREUR : '+ errMsg +'</span>';
      else
        div.innerHTML += 'Effectu&eacute;e.<BR>';
      ById('ptWildCancel').firstChild.innerHTML = 'FERMER'; 
      return;
    }
    if (div.innerHTML != '')
      div.innerHTML += 'Effectu&eacute;e.<BR>';
    var wild = Seed.wilderness['city'+ t.buildList.cityId]['t'+what[1]];
    if (what[0] == 'T'){
      div.innerHTML += 'Construction de '+ what[2] +' pi&egrave;ges sur '+ Cities.byID[t.buildList.cityId].name +'\' sur Terres au '+ wild.xCoord +','+ wild.yCoord +' ... ';
      t.postBuyTraps (t.buildList.cityId, what[1], what[2], t.processQue);
    } else {
      div.innerHTML += 'Configure Mercenaires -'+ mercNames[what[2]] +'- sur '+ Cities.byID[t.buildList.cityId].name +'\' sur Terres au '+ wild.xCoord +','+ wild.yCoord +' ... ';
      t.postHireMercs (t.buildList.cityId, what[1], what[2], what[3], t.processQue);
    }
  },
  
  setPopup : function (onoff){
    var t = Tabs.Wilds;
    if (onoff){
      var div = document.createElement('div');
      div.id = 'ptWildPop';
      div.style.backgroundColor = '#fff';
      div.style.zindex = mainPop.getLayer()+2;
      div.style.opacity = '1';
      div.style.border = '3px outset red';
      div.style.width = '550px';
      div.style.height = '300px';
      div.style.display = 'block';
      div.style.position = 'absolute';
      div.style.top = '100px';
      div.style.left = '100px';
      t.cont.appendChild (div);
      return div;
    } else {
      t.cont.removeChild (ById('ptWildPop'));
    }
  },

  setCurtain : function (onoff){
    var t = Tabs.Wilds;
    if (onoff){
      var off = getAbsoluteOffsets (t.cont);
      var curtain = document.createElement('div');
      curtain.id = 'ptWildCurtain';
      curtain.style.zindex = mainPop.getLayer()+1;
      curtain.style.backgroundColor = "#000000";
      curtain.style.opacity = '0.5';
      curtain.style.width = t.cont.clientWidth +'px';
      curtain.style.height = t.cont.clientHeight +'px';
      curtain.style.display = 'block';
      curtain.style.position = 'absolute';
      curtain.style.top = off.top + 'px';
      curtain.style.left = off.left + 'px';
      t.cont.appendChild (curtain);
    } else {
      t.cont.removeChild (ById('ptWildCurtain'));
    }
  },
  
  e_butMaxTraps : function (e){
    var t = Tabs.Wilds;
    var c = e.id.substr(5,1);
    var w = e.id.substr(7);
    var inp = ById('ptwt_'+ c +'_'+ w);
    inp.value = t.wildList[c][w][1];
    t.e_inpTraps (inp);
  },
  
  e_inpTraps : function (e){
    var t = Tabs.Wilds;
    var c = e.id.substr(5,1);
    var w = e.id.substr (7);
    var tot = 0;
    for (var i=0; i<t.wildList[c].length; i++) {   
      var val = parseInt(ById('ptwt_'+ c +'_'+ i).value, 10);
      if (isNaN(val))
        val = 0;
      tot += val;
    }  
    ById('ptwgc_'+ c).innerHTML = addCommasInt(tot * 200);
    if (isNaN(e.value) || e.value<0 || e.value>t.wildList[c][w][1]){
      e.value = '';
      e.style.backgroundColor = '#ffaaaa'; 
    } else
      e.style.backgroundColor = null; 
  },
  
  updateGold : function (){
    var t = Tabs.Wilds;
    for (var c=0; c<Cities.numCities; c++){
      var e = ById('ptwgt_'+ c +'');
      if (e)
        e.innerHTML = addCommasInt(Seed.citystats['city'+Cities.cities[c].id].gold[0]);
    }
  },
  
  postBuyTraps : function (cid, tid, quant, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = cid;
    params.tid = tid;
    params.quant = quant;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/buyWildTraps.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (rslt.ok){
         if (!Seed.wildDef["t"+ tid])
          Seed.wildDef["t"+ tid] = {tileId:tid, fort60Count:0, mercLevel:0};
          Seed.wildDef["t"+ tid].fort60Count = parseInt(Seed.wildDef["t"+ tid].fort60Count) + parseInt(quant);
         }  
         if (notify)
          notify (rslt.errorMsg);
      },
      onFailure: function () {
        if (notify)
          notify ('AJAX ERROR');
      },
    });
  },

  postHireMercs : function (cid, tid, newLevel, oldLevel, notify){

    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = cid;
    params.tid = tid;
    params.lv = newLevel;
    params.olv = oldLevel;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/hireWildMerc.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (rslt.ok){
          if (!Seed.wildDef["t"+ tid])
            Seed.wildDef["t"+ tid] = {tileId:tid, fort60Count:0, mercLevel:0};
          Seed.wildDef["t"+ tid].mercLevel = newLevel;
        }
        if (notify)
          notify (rslt.errorMsg);
      },
      onFailure: function () {
        if (notify)
          notify ('AJAX ERROR');
      },
    });
  },        
}    

/*********** AUTO CONSTRUCTION *********/
Tabs.build = {
    tabOrder: 11,
    tabLabel: uW.g_js_strings.commonstr.build,
    myDiv: null,
    timer: null,
    buildTab: null,
    koc_buildslot: null,
    currentBuildMode: null,
    buildStates: [],
	loaded_bQ: [],
	lbQ: [],

    init: function(div){
        var t = Tabs.build;
        t.myDiv = div;
        t.koc_buildslot = unsafeWindow.buildslot; 
        t.currentBuildMode = "build";
		t.buildStates = {
            running: false,
			help: false,
        };
        t.readBuildStates();
        
	AddSubTabLink('Constr', t.toggleStateRunning, 'pbbuildtab');
		

        for (var i = 0; i < Cities.cities.length; i++) {
            t["bQ_" + Cities.cities[i].id] = JSON2.parse(GM_getValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, '[]'));
			if (typeof t["bQ_" + Cities.cities[i].id] == 'undefined' || (t["bQ_" + Cities.cities[i].id]) == "") {
				t["bQ_" + Cities.cities[i].id] = [];
			}
        }
        
        var m = '<DIV id=pbBuildDivF class=boStat>AUTO-CONSTRUCTION - CONFIGURATION</div><TABLE id=pbbuildfunctions width=100% height=0% class=pbTab><TR>';
        if (t.buildStates.running == false) {
            m += '<TD><INPUT id=pbBuildRunning type=submit value="Auto Construction = OFF"></td>';
	       updatebotbutton('Constr - OFF', 'pbbuildtab');
        }
        else {
            m += '<TD><INPUT id=pbBuildRunning type=submit value="Auto Construction = ON"></td>';
	       updatebotbutton('Constr - ON', 'pbbuildtab');
        }
	m += '<TD><INPUT id=pbBuildMode type=submit value="Mode Construction = OFF"></td>';
			m += '<TD>Build Type: <SELECT id="pbBuildType">\
				<OPTION value=build>'+uW.g_js_strings.commonstr.next+'</option>\
				<OPTION value=max>'+uW.g_js_strings.commonstr.maximum+'</option>\
				<OPTION value=destruct>'+uW.g_js_strings.commonstr.destroy+'</option>\
				</select></td>';
		m += '<TD><INPUT id=pbHelpRequest type=checkbox '+ (t.buildStates.help?' CHECKED':'') +'\></td><TD>'+uW.g_js_strings.commonstr.helprequest+'</td>';
		m += '</tr></table></div>';
        m += '<DIV id=pbBuildDivQ class=boStat>CONSTRUCTION EN COURS</div><TABLE id=pbbuildqueues width=100% height=0% class=ptentry><TR>';
		for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><B>' + Cities.cities[i].name + '</b></center></td>';
        }
		m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><INPUT id=pbbuild_' + Cities.cities[i].id + ' type=submit value="'+uW.g_js_strings.commonstr.view+'"></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><INPUT id=pbCancelAll_' + Cities.cities[i].id + ' type=submit value="'+uW.g_js_strings.modaltitles.deleteall+'"></center></td>';
        }
        m += '</tr><TR>';
        
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD>Fil:</td><TD id=pbbuildcount_' + Cities.cities[i].id + '>' + t["bQ_" + Cities.cities[i].id].length + '</td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            t['totalTime_' + Cities.cities[i].id] = 0;
            cbQ = t["bQ_" + Cities.cities[i].id];
            if (typeof cbQ != 'undefined') {
                for (var j = 0; j < cbQ.length; j++) {
                    t['totalTime_' + Cities.cities[i].id] = parseInt(t['totalTime_' + Cities.cities[i].id]) + parseInt(cbQ[j].buildingTime);
                }
                timestring = timestr(t['totalTime_' + Cities.cities[i].id]);
            }
            m += '<TD>Tp:</td><TD id=pbbuildtotal_' + Cities.cities[i].id + '>' + timestring + '</td>';
        }
        m += '</tr></table><SPAN class=boldRed id=pbbuildError></span>';
        t.myDiv.innerHTML = m;
        
        for (var i = 0; i < Cities.cities.length; i++) {
            var cityId = Cities.cities[i].id;
            var btnName = 'pbbuild_' + cityId;
            addQueueEventListener(cityId, btnName);
            var btn2Name = 'pbCancelAll_' + cityId;
            CancelAllEventListener(cityId, btn2Name);
			t.showBuildQueue(cityId, false);
        }

        t.e_autoBuild();
        
		ById('pbBuildType').addEventListener('change', function(){t.setBuildMode(this.value);}, false);
		ById('pbBuildRunning').addEventListener('click', function(){
            t.toggleStateRunning(this);
        }, false);
		ById('pbBuildMode').addEventListener('click', function(){
            t.toggleStateMode(this);
        }, false);
		ById('pbHelpRequest').addEventListener ('change', function (){
        t.buildStates.help = (ById('pbHelpRequest').checked);
        t.saveBuildStates();
        }, false);
   	    
		window.addEventListener('unload', t.onUnload, false);
        
        function addQueueEventListener(cityId, name){
            ById(name).addEventListener('click', function(){
                t.showBuildQueue(cityId, true);
            }, false);
        }
        
        function CancelAllEventListener(cityId, name){
            ById(name).addEventListener('click', function(){
            	t["bQ_" + cityId] = [];
            	t['totalTime_' + cityId] = 0;
            	ById('pbbuildcount_' + cityId).innerHTML = 0;
            	ById('pbbuildtotal_' + cityId).innerHTML = timestr(0);
            }, false);
        }
        
        
    },
	setBuildMode: function (type) {
	    var t = Tabs.build;
		t.currentBuildMode = type;
		},	
    e_autoBuild: function(){
      var t = Tabs.build;
      var ilya=0;
      ById('pbbuildError').innerHTML = '';
      if (t.buildStates.running == true) {
          var now = unixTime();
          for (var i = 0; i < Cities.cities.length; i++) {
              var cityId = Cities.cities[i].id;
              var isBusy = false;
              var qcon = Seed.queue_con["city" + cityId];
              if (matTypeof(qcon)=='array' && qcon.length>0) {
                if (parseInt(qcon[0][4]) > now)
                  isBusy = true;
                else
                  qcon.shift();      
              }                            
              if (isBusy) {
                  //TODO add info of remaining build time and queue infos
              } else {
                 if (t["bQ_" + cityId].length > 0) { // something to do?
                 	 var bQi = t["bQ_" + cityId][0];   //take first queue item to build
			 t.doOne(bQi);             
               }
              } 
              ilya+=t["bQ_" + cityId].length
            }
            if (ilya==0) {
             t.toggleStateRunning();
             return;
            }
           setTimeout(t.e_autoBuild, 10000); //should be at least 10 
       }

    },  
    doOne : function (bQi){
		var t = Tabs.build;
		var currentcityid = parseInt(bQi.cityId);
		var cityName = t.getCityNameById(currentcityid);
		var time = parseInt(bQi.buildingTime);
		var mult = parseInt(bQi.buildingMult);
		var attempt = parseInt(bQi.buildingAttempt);
		var mode = bQi.buildingMode;
		var citpos = parseInt(bQi.buildingPos);	
		if (Seed.buildings['city' + currentcityid]["pos" + citpos] != undefined && Seed.buildings['city' + currentcityid]["pos" + citpos][0] != undefined) {	
			var l_bdgid = parseInt(bQi.buildingType);
			var bdgid = parseInt(Seed.buildings['city' + currentcityid]["pos" + citpos][0]);	
			var l_curlvl = parseInt(bQi.buildingLevel); 
			var curlvl = parseInt(Seed.buildings['city' + currentcityid]["pos" + citpos][1]);
			var l_bid = parseInt(bQi.buildingId);
			var bid = parseInt(Seed.buildings["city" + currentcityid]["pos" + citpos][3]);
		
			if (curlvl > 8 && mode == 'build') {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog("AutoCons","Queue item deleted: Building Level equals 9 or higher!!!");
				return;
			};
			if (isNaN(curlvl)) {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog("AutoCons","Found no correct value for current building!!!!");
				return;
			}
			if (l_bdgid != bdgid) {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog("AutoCons","Building Type does not match!!!!");
				return;
			}
			if (l_bid != bid) {
				t.cancelQueueElement(0, currentcityid, time, false);
				actionLog("AutoCons","Building ID does not match!!!!");
				return;
			}
			if (l_curlvl < curlvl) {
					t.cancelQueueElement(0, currentcityid, time, false);
					actionLog("AutoCons","Queue item deleted: Buildinglevel is equal or higher!!!");
					return;
			}
			if (l_curlvl > curlvl && mode == 'build') {
					t.requeueQueueElement(bQi);
					return;
			}

			if (mode == 'destruct') {
				var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
				params.cid = currentcityid;
				params.bid = "";
				params.pos = citpos;
				params.lv = curlvl - 1;
				if (curlvl >= 1) {
					params.bid = bid;
				}
				params.type = bdgid;
				new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/destruct.php" + unsafeWindow.g_ajaxsuffix, {
					method: "post",
					parameters: params,
					onSuccess: function(rslt){
						if (rslt.ok) {
							
							Seed.queue_con["city" + currentcityid].push([bdgid, 0, parseInt(rslt.buildingId), unsafeWindow.unixtime(), unsafeWindow.unixtime() + time, 0, time, citpos]);
							if (params.cid == unsafeWindow.currentcityid)
								unsafeWindow.update_bdg();
							if (ById('pbHelpRequest').checked == true)
								t.bot_gethelp(params.bid, currentcityid);
							t.cancelQueueElement(0, currentcityid, time, false);
						} else {
							var errmsg = unsafeWindow.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);
							t.requeueQueueElement(bQi);
							ById('pbbuildError').innerHTML = errmsg;
							
						}
					},
					onFailure: function(){
						ById('pbbuildError').innerHTML = "Erreur pendant la destruction !";
					}
				})
			}
			if (mode == 'build') {
				var invalid = false;
				var chk = unsafeWindow.checkreq("bdg", bdgid, curlvl);
				for (var c = 0; c < chk[3].length; c++) {
					if (chk[3][c] == 0) {
						invalid = true;
					}
				}
				if (invalid == false) {							
					var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
					params.cid = currentcityid;
					params.bid = "";
					params.pos = citpos;
					params.lv = curlvl + 1;
					if (params.lv > 9){ 
						t.cancelQueueElement(0, currentcityid, time, false);
						actionLog("AutoCons","Queue item deleted: Tryed to build level 10+ building! Please report if this happens!!!");
						return;
					}
					if (params.lv > 1) {
						params.bid = bid;
					}
					params.type = bdgid;
					
					new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/construct.php" + unsafeWindow.g_ajaxsuffix, {
						method: "post",
						parameters: params,
						onSuccess: function(rslt){
							if (rslt.ok) {
								Seed.resources["city" + currentcityid].rec1[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][1]) * mult * 3600;
								Seed.resources["city" + currentcityid].rec2[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][2]) * mult * 3600;
								Seed.resources["city" + currentcityid].rec3[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][3]) * mult * 3600;
								Seed.resources["city" + currentcityid].rec4[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][4]) * mult * 3600;
								Seed.citystats["city" + currentcityid].gold[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][5]) * mult;
								Seed.queue_con["city" + currentcityid].push([bdgid, curlvl + 1, parseInt(rslt.buildingId), unsafeWindow.unixtime(),  unsafeWindow.unixtime() + time, 0, time, citpos]);						
								if (params.cid == unsafeWindow.currentcityid)
									unsafeWindow.update_bdg();
								if (ById('pbHelpRequest').checked == true)
									t.bot_gethelp(params.bid, currentcityid);
								t.cancelQueueElement(0, currentcityid, time, false);
							} else {
								var errmsg = unsafeWindow.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);
								if (rslt.error_code == 103) { 
									t.cancelQueueElement(0, currentcityid, time, false);
									actionLog("AutoCons","Queue item deleted: Building at this Level already exists or build process already started!");
								} else {
									t.requeueQueueElement(bQi);
									ById('pbbuildError').innerHTML = Cities.byID[currentcityid].name +': '+ errmsg + " Item was requeued. Check for retry count.";
								}
								
							}
					},
						onFailure: function(){
							ById('pbbuildError').innerHTML = "Connection Error while building! Please try later again";
						}
					});
				} else {
					t.requeueQueueElement(bQi); 
				}
			}
		} else {
			t.cancelQueueElement(0, currentcityid, time, false);
			actionLog("AutoCons","Queue item deleted: Building does not exist!!!");
		}
	},
	requeueQueueElement: function (bQi) {
	    var t = Tabs.build;
		var cityId = bQi.cityId;
		var buildingPos = parseInt(bQi.buildingPos);
		var buildingId = parseInt(bQi.buildingId);
		var buildingLevel = parseInt(bQi.buildingLevel);
		var buildingType = parseInt(bQi.buildingType);
		var buildingTime = parseInt(bQi.buildingTime);
		var buildingMult = parseInt(bQi.buildingMult);
		var buildingAttempts = parseInt(bQi.buildingAttempts);
		var buildingMode = bQi.buildingMode;
		
		t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts + 1, buildingMult, buildingMode);
		t.cancelQueueElement(0, cityId, buildingTime, false); 
	},
    show: function(){
		var t = Tabs.build;
    },
    bot_buildslot: function(c, a){
        var t = Tabs.build;
		var cityId = t.getCurrentCityId();
        	var buildingPos   = c.id.split("_")[1];
        	var buildingType  = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][0]);
        	var buildingLevel = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
		var buildingId    = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][3]);
  		var buildingAttempts = 0;
		var loaded_bQ = t["bQ_" + cityId];
		if (typeof Seed.queue_con['city' + cityId][0] != 'undefined') {
			var current_construction_pos = Seed.queue_con['city' + cityId][0][2];
		} else {
			var current_construction_pos = "";
		}
		if (loaded_bQ.length == 0 && current_construction_pos != "" ) { 
			if (current_construction_pos != 'NaN' && current_construction_pos == buildingId) {
				buildingLevel += 1;
			}
		} else {
			if (current_construction_pos != "" && current_construction_pos == buildingId) {
				buildingLevel += 1;
			}
			for (var i = 0; i < loaded_bQ.length; i++) { 
				var loadedCity = loaded_bQ[i].cityId;
				var loadedSlot = loaded_bQ[i].buildingPos;
				if (loadedSlot == buildingPos && loadedCity == cityId) {
					buildingLevel += 1;
				}
				if (loaded_bQ[i].buildingMode == 'destruct' && loadedSlot == buildingPos && loadedCity == cityId) { 
					t.modalmessage('Destruction already in Queue!');
					return;
				}
			}
		}
        if (t.currentBuildMode == "build") {
	   if (buildingLevel >= 9) {
                t.modalmessage('La construction des niveaux 10 ou + doivent se faire manuellement.');
                return;
            }
            var buildingMode = "build";
			var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
			var buildingMult = result[0];
			var buildingTime = result[1];
			var queueId = loaded_bQ.length;
			t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
			t._addTab(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode);
        }
        if (t.currentBuildMode == "max") {
            var buildingMode = "build";
			for (var bL = buildingLevel; bL <9; bL++) {
				var queueId = loaded_bQ.length;
				var result = t.calculateQueueValues(cityId, bL, buildingType, buildingMode);
				var buildingMult = result[0];
				var buildingTime = result[1];
				queueId = queueId ;
				t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult, buildingMode);
				t._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
			}
        }
        if (t.currentBuildMode == "destruct") {
            var buildingMode = "destruct";
			var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
			var buildingMult = result[0];
			var buildingTime = result[1];
			var queueId = loaded_bQ.length;
			t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
			t._addTab(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode);
        }

    },
	calculateQueueValues: function (cityId, buildingLevel, buildingType, buildingMode) {
	    var t = Tabs.build;
		var now = unixTime();
		if (buildingMode == 'build') {
			var buildingMult = Math.pow(2, buildingLevel);
        } 
		if (buildingMode == 'destruct') {
			var buildingMult = Math.pow(2, buildingLevel - 2);
		}
				
		var knights = Seed.knights["city" + cityId];
		if (knights) {
			var polKniId = parseInt(Seed.leaders['city' + cityId].politicsKnightId);
			if (polKniId) {
				var polValue = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politics);
				var polBoost = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politicsBoostExpireUnixtime);
				if ((polBoost - now) > 0) {
					polValue = parseInt(polValue * 1.25);
				}
			} else {
				polValue = 0;
			}
		} else {
			polValue = 0;
		}
        
        var buildingTime = unsafeWindow.buildingcost["bdg" + buildingType][7] * buildingMult;
        
        
        
        if (parseInt(buildingType) < 6 && parseInt(buildingType) > 0 && buildingMult == 1) {
            buildingTime = 15;
        }
        var C=uW.cm.ThroneController.effectBonus(78);
        
	if (buildingMode == 'build') {
			buildingTime = parseInt(buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16)));
			
        } 
	if (buildingMode == 'destruct') {
			buildingTime = parseInt(buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16)));
			if (buildingTime % 1 > 0) {
				buildingTime = parseInt(buildingTime);
			}
		}
	 buildingTime=Math.round(buildingTime/(1+(C/100)));	
	 var result = new Array(buildingMult, buildingTime);
	 return result;
	},
	calculateQueueValues: function (cityId, buildingLevel, buildingType, buildingMode) {
	    var t = Tabs.build;
		var now = unixTime();
		if (buildingMode == 'build') {
			var buildingMult = Math.pow(2, buildingLevel);
        } 
		if (buildingMode == 'destruct') {
			var buildingMult = Math.pow(2, buildingLevel - 2);
		}
				
		var knights = Seed.knights["city" + cityId];
		if (knights) {
			var polKniId = parseInt(Seed.leaders['city' + cityId].politicsKnightId);
			if (polKniId) {
				var polValue = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politics);
				var polBoost = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politicsBoostExpireUnixtime);
				if ((polBoost - now) > 0) {
					polValue = parseInt(polValue * 1.25);
				}
			} else {
				polValue = 0;
			}
		} else {
			polValue = 0;
		}
        
        var buildingTime = unsafeWindow.buildingcost["bdg" + buildingType][7] * buildingMult;
        if (parseInt(buildingType) < 6 && parseInt(buildingType) > 0 && buildingMult == 1) {
            buildingTime = 15;
        }
		if (buildingMode == 'build') {
			buildingTime = parseInt(buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16)));
        }
		if (buildingMode == 'destruct') {
			buildingTime = buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16));
			if (buildingTime % 1 > 0) {
				buildingTime = parseInt(buildingTime);
			}
		}
		
		var result = new Array(buildingMult, buildingTime);
		return result;
	},
	bot_gethelp: function (f, currentcityid) {
		var t = Tabs.build;
		var city = t.getCityNameById(currentcityid);
		for (i=0;i<Seed.cities.length;i++) {
			if (Seed.cities[i][1]==city) var cityNum=i;
		}
		cityNum++;
		unsafeWindow.citysel_click(ById('citysel_'+ (cityNum)));
	  var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
	  params.bid = f;
	  params.ctrl = 'AskForHelp';
	  params.action = 'getHelpData';
	  new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
		  method: "post",
		  parameters: params,
		  onSuccess: function (rslt) {
			unsafeWindow.handleHelpCallback (rslt.data);
		  },
		  onFailure: function (rslt) {
			t.bot_gethelp (f, currentcityid);
			return;
		  },
		  });

	  var a = Seed.queue_con["city" + currentcityid];
	  var e = 0;
	  var d = 0;
	  for (var c = 0; c < a.length; c++) {
		if (parseInt(a[c][2]) == parseInt(f)) {
		  e = parseInt(a[c][0]);
		  d = parseInt(a[c][1]);
		  break
		}
	  }
	  var b = new Array();
	  b.push(["REPLACE_LeVeLbUiLdInG", d]);
	  b.push(["REPLACE_BuIlDiNgNaMe", unsafeWindow.buildingcost["bdg" + e][0]]);
	  b.push(["REPLACE_LeVeLiD", d]);
	  b.push(["REPLACE_AsSeTiD", f]);
	  var g = function(h, i) {
		unsafeWindow.continuation_95(h, i);
		if (!h) {
		  var j = d > 1 ? unsafeWindow.cm.SpeedUpType.upgrade : unsafeWindow.cm.SpeedUpType.build;
		  unsafeWindow.cm.ClientSideCookieManager.setCookie(j, false)
		}
	  };
	  unsafeWindow.common_postToProfile("95", unsafeWindow.Object.cloneFeed(unsafeWindow.template_data_95), unsafeWindow.Object.cloneFeed(unsafeWindow.actionlink_data_95), g, b)
	},
	addQueueItem: function (cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode) {
	var t = Tabs.build;
		var lbQ = t["bQ_" + cityId];
		lbQ.push({
            cityId: 			cityId,
            buildingPos:		buildingPos,
            buildingType: 		buildingType,
			buildingId: 		buildingId,
            buildingTime: 		buildingTime,
            buildingLevel: 		buildingLevel,
            buildingAttempts: 	buildingAttempts,
			buildingMult: 		buildingMult,
            buildingMode: 		buildingMode
        });
	t.modifyTotalTime(cityId, 'increase', buildingTime);
	},
    modalmessage: function(message){
	var t = Tabs.build;
        var timeout = 10000;
        var content = "Fermeture automatique dans 10 sec...<br><br>"
        content += message;
        unsafeWindow.Modal.showAlert(content);
        setTimeout(function() {
          unsafeWindow.Modal.hideModal();
        }, timeout);
    },
	modifyTotalTime: function (cityId, type, buildingTime) {
	    var t = Tabs.build;
		var element = ById('pbbuildcount_' + cityId);
		var currentCount = parseInt(element.innerHTML);
		if (type == "increase") {
			t['totalTime_' + cityId] = t['totalTime_' + cityId] + buildingTime;
			var currentCount = currentCount + 1;
		}
		if (type == "decrease") {
			t['totalTime_' + cityId] = t['totalTime_' + cityId] - buildingTime;
			var currentCount = currentCount - 1;
		}
		element.innerHTML = currentCount;
		ById('pbbuildtotal_' + cityId).innerHTML = timestr(t['totalTime_' + cityId]);
	},
    hide: function(){
        var t = Tabs.build;
    },
    onUnload: function(){
        var t = Tabs.build;
        for (var i = 0; i < Cities.cities.length; i++) {
            if (!ResetAll) GM_setValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, JSON2.stringify((t["bQ_" + Cities.cities[i].id])));
        }
        t.saveBuildStates();
    },
    _addTab: function(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode){
		var t = Tabs.build;
        var row = ById('pbCityQueueContent').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = queueId;
        if (buildingMode == "destruct") {
            row.insertCell(1).innerHTML = '<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/bonus_att.png">';
        }
        else {
            row.insertCell(1).innerHTML = '<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/bonus_prod.png">';
        }
        row.insertCell(2).innerHTML = unsafeWindow.buildingcost['bdg' + buildingType][0];
        row.insertCell(3).innerHTML = timestr(buildingTime);
		if (buildingMode == "destruct") {
			row.insertCell(4).innerHTML = 0;
        } else {
			row.insertCell(4).innerHTML = buildingLevel + 1;
		}
		row.insertCell(5).innerHTML = buildingAttempts;
        row.insertCell(6).innerHTML = '<a class="button20" id="queuecancel_' + queueId + '"><span>'+uW.g_js_strings.commonstr.cancel+'</span></a>';
        ById('queuecancel_' + queueId).addEventListener('click', function(){
            t.cancelQueueElement(queueId, cityId, buildingTime, true);
        }, false);
    },
    cancelQueueElement: function(queueId, cityId, buildingTime, showQueue){
        var t = Tabs.build;
        var queueId = parseInt(queueId);
        t["bQ_" + cityId].splice(queueId, 1);
        t.modifyTotalTime(cityId, 'decrease', buildingTime); 	
        
        if (showQueue == true) {
            t.showBuildQueue(cityId, false);
        }
    },
    showBuildQueue: function(cityId, focus){
	    var t = Tabs.build;
	    clearTimeout (t.timer);
        var popBuildQueue = null;
        var cityName = t.getCityNameById(cityId);
        if (t.popBuildQueue == null) {
            t.popBuildQueue = new CPopup('pbbuild_' + cityId, 0, 0, 350, 500, true, function() {clearTimeout (t.timer);});
        }
        var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbTabPad" id="pbCityQueueContent">';       
        t.popBuildQueue.getMainDiv().innerHTML = '</table></div>' + m;
        t.popBuildQueue.getTopDiv().innerHTML = '<TD width="200px"><B>File d\'attente de' + cityName + '</b></td><TD><INPUT id=pbOptimizeByTime type=submit value="Optimiser par temps"></td>';
        t.popBuildQueue.centerMe (mainPop.getMainDiv());
        
        t.paintBuildQueue(cityId);
        if (focus)
          t.popBuildQueue.show(true);
		ById('pbOptimizeByTime').addEventListener('click', function(){t.clearBuildQueue();t.paintBuildQueue(cityId, true);}, false);
		t.timer = setTimeout (function() {t.showBuildQueue(cityId, false)}, 45000);  
	},
    paintBuildQueue: function(cityId, optimize){
        var t = Tabs.build;
        var lbQ = t["bQ_" + cityId];
		if (optimize == true) {
			lbQ.sort(function(a,b){return a.buildingTime - b.buildingTime});
		}
		t["bQ_" + cityId] = lbQ;
		for (var i = 0; i < lbQ.length; i++) {
			var queueId = i;
			t._addTab(queueId, lbQ[i].cityId, lbQ[i].buildingType, lbQ[i].buildingTime, lbQ[i].buildingLevel, lbQ[i].buildingAttempts, lbQ[i].buildingMode);
        }
    },
    clearBuildQueue: function() {
	    var t = Tabs.build;
		var table = ById('pbCityQueueContent');
		var rows = table.rows;
		while(rows.length)
			table.deleteRow(rows.length-1);
	},
    getCurrentCityId: function(){ 
        if (!unsafeWindow.currentcityid)
            return null;
        return unsafeWindow.currentcityid;
    },
    saveBuildStates: function(){
		var t = Tabs.build;
        var serverID = getServerId();
        GM_setValue('buildStates_' + serverID, JSON2.stringify(t.buildStates));
    },
    readBuildStates: function(){
        var t = Tabs.build;
        var serverID = getServerId();
        s = GM_getValue('buildStates_' + serverID);
        if (s != null) {
            states = JSON2.parse(s);
            for (k in states)
                t.buildStates[k] = states[k];
        }
    },
    toggleStateRunning: function(obj){
		var t = Tabs.build;
		obj = ById('pbBuildRunning');
        if (t.buildStates.running == true) {
            t.buildStates.running = false;
            t.saveBuildStates();
            if (obj) obj.value = "Auto Construction = OFF";
	      updatebotbutton('Constr - OFF', 'pbbuildtab');
        }
        else {
            t.buildStates.running = true;
            t.saveBuildStates();
            if (obj) obj.value = "Auto Construction = ON";
	    updatebotbutton('Constr - ON', 'pbbuildtab');
	    t.e_autoBuild(); 
        }
    },
    toggleStateMode: function(obj){
		var t = Tabs.build;
		obj = ById('pbBuildMode');
            if (obj.value == 'Mode Construction = OFF') {
			unsafeWindow.buildslot = t.bot_buildslot; 
            obj.value = "Mode Construction = ON";
	    
        }      else {
			unsafeWindow.buildslot = t.koc_buildslot;
			obj.value = "Mode Construction = OFF";
        }
    },
	getCityNameById: function (cityId) {
    return Cities.byID[cityId].name;  	
	},
}    
/**************************** CHEVALIERS *********************/ 
Tabs.Knights = {
 tabOrder: 9,
  tabLabel: uW.g_js_strings.commonstr.knight,
  cont : null,
  state : null,
  displayTimer : null,
  action : 0,
  show : function (){
    var t = Tabs.Knights;
  },
  hide : function (){
    var t = Tabs.Knights;
    clearTimeout (t.displayTimer);
  },
  init : function (div){
    var t = Tabs.Knights;
    unsafeWindow.ptAssignSkill = t.clickedAssignPoints;
    unsafeWindow.ptAssignTunes = t.clickedAssignTune;  
    t.cont=div;
    clearTimeout (t.displayTimer);
    if (t.state == null){
      t.cont.innerHTML = '<STYLE>table.ptTabPad tr.ptwpad {background-color:#ffffff; padding-left:5px}</style>\
            <DIV id=ptknightdiv style="max-height:'+(Options.HauteurBoite-25)+'px; height:'+(Options.HauteurBoite-25)+'px; overflow-y:auto">';
      t.state = 1;
    }
    t.showDiv();
   },
   showDiv: function() {
    var t = Tabs.Knights;
    function _dispKnight (roleId, knight, numcid){
      var rid = roleId;
      if (roleId==null)
        rid = 1;
      var sty='';  
      if (row++ % 2)
        sty = ' ';        
      m = '<TR '+ sty +'valign=top align=right><TD><font size=1><B>'+ (roleId==null ? '':knightRoles[rid][0]) +'</b></td><TD align=left>';
      if (knight == null) {
        m += '--------</td><TD colspan=5></td><TD class=ptentry colspan=5></td><TD colspan=2></td></tr>';
      } else {
        var level = parseInt(Math.sqrt(parseInt(knight.experience) / 75)) + 1;
        var unpoints = level - parseInt(knight.skillPointsApplied);
        var salary = (parseInt(knight.skillPointsApplied) + 1) * 20;
        totSalary += salary;
        var ass = '';
        if (knight.knightStatus == 10){
          ass = '<TD class=ptentry align=left colspan=4>'+uW.g_js_strings.commonstr.marching+'</td>';
        } else {  
          if (unpoints > 0){
            unpoints = '<SPAN class="boldRed">'+ unpoints +'</span>';
            for (var i=0; i<4; i++){
            var sty = 'padding-left:1px;';
            if (i == rid) { 
              sty += 'font-weight:bold;color:#116654';
              if (t.action==1) {   
	          t.clickedAssignPoints(null, cid,knight.knightId,i);
              }
              if (t.action==2) {   
	      	          t.clickedAssignPoints(null, cid,knight.knightId,1);
              }
            }
            ass += '<TD class=ptentry align=left style="'+ sty +'" ><A style="'+ sty +'" onclick="ptAssignSkill(this,' + cid +','+ knight.knightId +','+ i +')">['+ knightRoles[i][2] +'] &nbsp;</a></td>'; 
           }
          } 
          else
            ass = '<TD class=ptentry colspan=4></td>';
        }  
        var now = unixTime();
        var skills = [];
        for (var i=0; i<4; i++){
          if (i == rid) {
            var point = knight[knightRoles[i][1]];
            skills[i] = '<B>'+ point +'</b>'; 
            if (i==1 && knight.combatBoostExpireUnixtime > now) {
		point *= 1.25;
		skills[i] = '<font color=red><span title="Boost 25 % encore '+timestr(knight.combatBoostExpireUnixtime - now)+'"><B>'+ parseInt(point) +'</b></span></font>'; 
            }
             if (i==0 && knight.politicsBoostExpireUnixtime > now) {
	    		point *= 1.25;
	    		skills[i] = '<font color=red><span title="Boost 25 % encore '+timestr(knight.politicsBoostExpireUnixtime - now)+'"><B>'+ parseInt(point) +'</b></span></font>'; 
            }
             if (i==3 && knight.resourcefulnessBoostExpireUnixtime > now) {
	    		point *= 1.25;
	    		skills[i] = '<font color=red><span title="Boost 25 % encore '+timestr(knight.resourcefulnessBoostExpireUnixtime - now)+'"><B>'+ parseInt(point) +'</b></span></font>'; 
            }
             if (i==2 && knight.intelligenceBoostExpireUnixtime > now) {
	    		point *= 1.25;
	    		skills[i] = '<font color=red><span title="Boost 25 % encore '+timestr(knight.intelligenceBoostExpireUnixtime - now)+'"><B>'+ parseInt(point) +'</b></span></font>'; 
            }
           } else {
              var point = knight[knightRoles[i][1]];
	      skills[i] = ''+ point +''; 
	                 if (i==1 && knight.combatBoostExpireUnixtime > now) {
	     		point *= 1.25;
	     		skills[i] = '<font color=red><span title="Boost 25 % encore '+timestr(knight.combatBoostExpireUnixtime - now)+'">'+ parseInt(point) +'</span></font>'; 
	                 }
	                  if (i==0 && knight.politicsBoostExpireUnixtime > now) {
	     	    		point *= 1.25;
	     	    		skills[i] = '<font color=red><span title="Boost 25 % encore '+timestr(knight.politicsBoostExpireUnixtime - now)+'">'+ parseInt(point) +'</span></font>'; 
	                 }
	                  if (i==3 && knight.resourcefulnessBoostExpireUnixtime > now) {
	     	    		point *= 1.25;
	     	    		skills[i] = '<font color=red><span title="Boost 25 % encore '+timestr(knight.resourcefulnessBoostExpireUnixtime - now)+'">'+ parseInt(point) +'</span></font>'; 
	                 }
	                  if (i==2 && knight.intelligenceBoostExpireUnixtime > now) {
	     	    		point *= 1.25;
	     	    		skills[i] = '<font color=red><span title="Boost 25 % encore '+timestr(knight.intelligenceBoostExpireUnixtime - now)+'">'+ parseInt(point) +'</span></font>'; 
            		 }
           }
        }   
        var item211="0";
        var item221="0";
        var item231="0";
        var item241="0";
        if (Seed.items.i211) item211='<a onclick="citysel_click(document.getElementById(\'citysel_'+ (numcid+1)+'\'));setTimeout (function (){ boost_modal(1,'+ knight.knightId +');return false;}, 500);">'+Seed.items.i211+'</a>';
        if (Seed.items.i221) item221='<a onclick="citysel_click(document.getElementById(\'citysel_'+ (numcid+1)+'\'));setTimeout (function (){ boost_modal(2,'+ knight.knightId +');return false;}, 500);">'+Seed.items.i221+'</a>';
        if (Seed.items.i231) item231='<a onclick="citysel_click(document.getElementById(\'citysel_'+ (numcid+1)+'\'));setTimeout (function (){ boost_modal(3,'+ knight.knightId +');return false;}, 500);">'+Seed.items.i231+'</a>';
        if (Seed.items.i241) item241='<a onclick="citysel_click(document.getElementById(\'citysel_'+ (numcid+1)+'\'));setTimeout (function (){ boost_modal(4,'+ knight.knightId +');return false;}, 500);">'+Seed.items.i241+'</a>';
        m += '<a title="Assigner un role" onclick="citysel_click(document.getElementById(\'citysel_'+ (numcid+1)+'\'));setTimeout (function (){ assign_role_modal('+ knight.knightId +');return false;}, 500);">' + knight.knightName.substring(0,20) + '</a></td><TD><a title="Augmenter EXP" onclick="citysel_click(document.getElementById(\'citysel_'+ (numcid+1)+'\'));setTimeout (function (){  xpBoost_modal('+ knight.knightId +');return false; }, 500);" href="javascript:void(0)">'+ level +'</a></td>\
              <TD>'+ skills[0] +' ('+item211+')</td><TD>'+ skills[1] +' ('+item221+')</td><TD>'+ skills[2] +' ('+item231+')</td><TD>' + skills[3]
          +' ('+item241+')</td><TD class=ptentry>'+ unpoints +'</td>'+ ass +'<td><a onclick="citysel_click(document.getElementById(\'citysel_'+ (numcid+1)+'\'));setTimeout (function (){ loyalBoost_modal('+ knight.knightId +');return false;}, 500);" colspan=2>'+knight.loyalty+'</a><img onclick="ptAssignTunes(' + cid +','+ knight.knightId +');" src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/gold_16.png" title="Booster la loyaute a 5% avec l\'or"></td><TD>'+ addCommas(salary) +'</td></tr>';
      }
      return m;
    }          
    
    var totSalary = 0;
    var m = '<TABLE cellspacing=0 align=center class=ptTabPad><TR><td colspan=15><DIV class=boStat>Gestion des chevaliers - <input style="height:20px;font-size:9px;" type=button value="Attribution par defaut" id="BOchebut"><input style="height:20px;font-size:9px;" type=button value="Attribution en combat" id="BOchebut1"></div></td></tr>';
    for (var c=0; c<Cities.numCities; c++) {
      var city = Cities.cities[c];
      var cid = Cities.cities[c].id;
      m += '<tr><TD colspan=15><DIV class=boStat>'+ Cities.cities[c].name +' &nbsp; ('+ city.x +','+ city.y +') </div></td></tr>\
          <TBODY id="BOkin'+cid+'"><TR style="font-weight:bold" align=right><TD width=70>Role</td><TD width=140 align=center>'+uW.g_js_strings.commonstr.nametx+'</td><TD width=22>Niv</td><TD width=25>Pol</td><TD width=25>Com</td>\
          <TD width=25>Int</td><TD width=25>Res</td><TD width=75 align=center colspan=5>-- '+uW.g_js_strings.modaltitles.assignskills+' --</td><td witdh=25 colspan=1>Loy</td><TD width=40 align=right> '+uW.g_js_strings.commonstr.salary+' </td></tr>';
      totSalary = 0;
      var did = {}; 
      var row = 0;
      for (var i=0; i<knightRoles.length; i++){
        var leader = Seed.leaders['city'+cid][knightRoles[i][1]+'KnightId'];
        if (leader == 0)
          m += _dispKnight (i, null, c);
        else {
          m += _dispKnight (i, Seed.knights['city'+cid]['knt'+leader], c);
          did['knt'+leader] = true;
        }
      }
      var list = [];
      for (k in Seed.knights['city'+cid]){
        if (!did[k])
          list.push (Seed.knights['city'+cid][k]);
      }
      list.sort (function (a,b){return parseInt(b.combat)-parseInt(a.combat)});
      for (i=0; i<list.length; i++)
        m += _dispKnight (null, list[i], c);
       m += '<TR align=right><TD colspan=13><B>'+uW.g_js_strings.commonstr.salary+' Total :</b></td><TD>'+ addCommas(totSalary) +'</td></tr></TBODY>';        
    }
    ById('ptknightdiv').innerHTML = m +'</table></div>';
    
     
    t.action = 0;
    but = ById('BOchebut');
    but.addEventListener ('click', function (){
      t.action=1;
      t.showDiv();
    }, false);
    but = ById('BOchebut1');
    but.addEventListener ('click', function (){
          t.action=2;
          t.showDiv();
    }, false);
    t.displayTimer = setTimeout (t.showDiv, 5000);
  },

  clickedAssignTune: function(cid, kid) {
    var t = Tabs.Knights;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = cid;
        params.kid = kid;
      params.rid=0;
      params.standalone=0;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/rewardKnight.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
       if (rslt.ok) {
         var knight = Seed.knights["city" + cid]["knt" + kid];
         knight.loyalty = parseInt(knight.loyalty) + 5;    
        }
      },
      onFailure: function () {
      }, 
    });
  },
  clickedAssignPoints : function (e, cid, kid, rid){
    var t = Tabs.Knights;
    clearTimeout (t.displayTimer);
      
    var knight = Seed.knights['city'+cid]['knt'+kid];
    if (knight.knightStatus == 10 && e!=null){
      var row = e.parentNode.parentNode;
      row.childNodes[7].innerHTML = uW.g_js_strings.commonstr.marching;
      return; 
    }
    sk = [];
    var unassigned = parseInt(Math.sqrt(parseInt(knight.experience)/75)) + 1  - parseInt(knight.skillPointsApplied);    
    
    
    for (var i=0; i<4; i++){
      sk[i] = parseInt(knight[knightRoles[i][1]]);
      if (i == rid) {
        if ((sk[i]+unassigned)>=255) {
          unassigned=255-sk[i];
          sk[i]=255;
          
        }else{
          sk[i] += unassigned;
        }
      }
    }
    if (unassigned==0) return;
    if (e!=null) {
     var row = e.parentNode.parentNode;
     for (i=row.cells.length-1; i>=1; i--)
      row.deleteCell (i);
     var newCell=row.insertCell(-1);
     newCell.colSpan = 12;
     newCell.align= 'left';
     newCell.style.padding='1px 5px 1px 10px';
     var div = document.createElement ('div');
     div.style.backgroundColor = '#ffffff';
     div.style.textAlign = 'center'; 
     div.style.border = '1px solid';
     div.style.width = '98%';
     div.style.whiteSpace = 'normal';
     newCell.appendChild (div);
     div.innerHTML = 'Assignation de '+ unassigned +' comp&eacute;tence(s) '+ knightRoles[rid][1] +' ... ';
    }
    t.postSkillPoints (cid, kid, sk[0], sk[1], sk[2], sk[3], function (r){t.postDone(r, div)});  
  },
  
  postDone : function (rslt, div){
    var t = Tabs.Knights;
    clearTimeout (t.displayTimer);
    if (rslt.ok){
      if (div) div.innerHTML += '<B>Effectu&eacute;e.</b>';
      t.displayTimer = setTimeout (t.showDiv, 5000);
    } else {
      if (div) div.innerHTML += '<BR><SPAN class=boldRed>ERREUR : '+ rslt.errorMsg +'</span>';
      t.displayTimer = setTimeout (t.showDiv, 10000);
    }
  },
  
  postSkillPoints : function (cid, kid, pol, com, int, res, notify){  
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = cid;
    params.kid = kid;
    params.p = pol;
    params.c = com;
    params.i = int;
    params.r = res;

    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/skillupKnight.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (rslt.ok) {
          var knight = Seed.knights["city" + cid]["knt" + kid];
          var up = pol + com + int + res - knight.politics - knight.combat - knight.intelligence - knight.resourcefulness;
          knight.politics = pol;
          knight.combat = com;
          knight.intelligence = int;
          knight.resourcefulness = res;
          knight.skillPointsApplied = (parseInt(knight.skillPointsApplied) + up).toString();
        } 
        if (notify)
          notify (rslt);
      },
      onFailure: function () {
        if (notify)
          notify (rslt);
      },
    });
  },
};

/******************* AUTO CRAFTING ************/
Tabs.AutoCraft = {

tabOrder: 14,
    tabLabel: 'AutoCraft',
    myDiv: null,
    timer: null,
    toutles  : 300,
    crafting: [],
    craftinfo : {},
myDiv: null,
    timer: null,
    timerStat: null,
    numcity :-1,
 init: function(div){
        var t = Tabs.AutoCraft;
        t.myDiv = div;   
        t.crafting = {
	            running: TrainOptions.CraftingRunning,
        };
        AddSubTabLink('Craft', t.toggleStateRunning, 'bocrafttab');
        var m = '<DIV id=pbBuildDivF class=boStat>AUTO-CRAFTING - CONFIGURATION</div><TABLE width=100% height=0% class=pbTab><TR>';
        if (t.crafting.running == false) {
	            m += '<TD><INPUT id=pbCraftRunning type=submit value="Auto Craft = OFF"></td>';
	            updatebotbutton("Craft - OFF", 'bocrafttab');
	 }	        else {
	            m += '<TD><INPUT id=pbCraftRunning type=submit value="Auto Craft = ON"></td>';
	            updatebotbutton("Craft - ON", 'bocrafttab');
	            t.timer=setInterval(t.Start,parseInt(t.toutles*1000));
        }
        m += '<td></td></tr></table></div>';
           m += '<DIV id=pbBuildDivQ class=boStat>STATISTIQUES</div><span id="BOCraftStat"></span>';
           m += '<DIV id=pbBuildDivQ class=boStat>OPTIONS - DEFINIR LES OBJETS A CREER</div><div style="height:' + (Options.HauteurBoite-200) +'px;max-height:' + (Options.HauteurBoite-200) +'px;overflow-y:auto"><TABLE width=100% height=0% class=ptTab><TR>';

        m += "<td colspan=2>Objet &agrave; cr&eacute;er</td><td>"+uW.g_js_strings.commonstr.inventory+"*</td><td>Qt&eacute; &agrave; cr&eacute;er</td><td colspan=2>Objet &agrave; cr&eacute;er</td><td>"+uW.g_js_strings.commonstr.inventory+"*</td><td>Qt&eacute; &agrave; cr&eacute;er</td></tr>"; 
        

        for(var i=0; i < unsafeWindow.recipelist[1].length; i++){
var h = parseInt(unsafeWindow.recipelist[1][i].output_item_id);
t.craftinfo[h] = {};
t.craftinfo[h].recipe_id = unsafeWindow.recipelist[1][i].recipe_id;
t.craftinfo[h].category = unsafeWindow.recipelist[1][i].category;
t.craftinfo[h].input = unsafeWindow.recipelist[1][i].input;
t.craftinfo[h].requirements = unsafeWindow.recipelist[1][i].requirements;
m += "<td ><center><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></center></td><td><center>"+unsafeWindow.itemlist["i"+h].name+"</center></td><td><center><span class=boldGreen>"+parseIntNan(Seed.items["i"+h])+"</span></center></td>";
m += "<td><input type=text size=4 id='BOCraft_nb_"+h+"' value='"+ parseIntNan(TrainOptions.CraftingNb[h]) +"'></td>";
if ((i+1)%2 == 0) m += "</tr><tr>";
}
for(var i=0; i < unsafeWindow.recipelist[3].length; i++){
var h = parseInt(unsafeWindow.recipelist[3][i].output_item_id);
t.craftinfo[h] = {};
t.craftinfo[h].recipe_id = unsafeWindow.recipelist[3][i].recipe_id;
t.craftinfo[h].category = unsafeWindow.recipelist[3][i].category;
t.craftinfo[h].input = unsafeWindow.recipelist[3][i].input;
t.craftinfo[h].requirements = unsafeWindow.recipelist[3][i].requirements;
m += "<td ><center><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></center></td><td><center>"+unsafeWindow.itemlist["i"+h].name+"</center></td><td><center><span class=boldGreen>"+parseIntNan(Seed.items["i"+h])+"</span></center></td>";

	 m += "<td><input type=text size=4 id='BOCraft_nb_"+h+"' value='"+ parseIntNan(TrainOptions.CraftingNb[h]) +"'></td>";
         if ((i+1)%2 == 0) m += "</tr><tr>";
 	}

        m+="</table><i><u>Note :</u> Avoir un minimun de 5 000 Aethestone</u></i> - <i>(*) Il faut rafraichir le jeu pour mettre le stock &agrave; jour.</i></div>";
       

       t.myDiv.innerHTML = m;
       
       window.addEventListener('unload', t.onUnload, false);
       
        ById("pbCraftRunning").addEventListener ('click', function (){t.toggleStateRunning(this)}, false); 
         
         
  }, 
  updateStat: function() {
   var t = Tabs.AutoCraft;
   var rownum = 0;
   function _row (name, row, noTotal, typee){
         if (rownum++ % 2)
           style = '';
         else
           style = ' style = "background: #e8e8e8"';
         var tot = 0;
         var m = [];
         m.push ('<TR style="background: #fff" align=right');
         m.push (style);
         m.push ('><TD');
         m.push (style);
         m.push ('><B>');
         m.push (name);
         m.push ('</td>');
         if (noTotal){
           m.push ('<TD');
           m.push (style);
           m.push ('>&nbsp;</td>');
         } else {
           for (i=0; i<row.length; i++)
             tot += row[i];
           m.push ('<TD style="background: #ffc">');
            if (tot<0) {
             m.push ("<SPAN class=boldRed>"+addCommas(tot)+"</span>");
            } else {
             m.push (addCommas(tot));
            }
           m.push ('</td>');
         }
         for (i=0; i<row.length; i++){
           m.push ('<TD');
           m.push (style);
           m.push ('>');
           if (row[i]<5000) {
	                m.push ("<SPAN class=boldRed>"+addCommas(row[i])+"</span>");
	   } else {
	                m.push (addCommas(row[i]));
           }
           m.push ('</td>');
         }
   
         m.push ('</tr>');
         return m.join('');
       }

   clearTimeout(t.timerStat);
   var str="<TABLE class=pbTab cellpadding=0 cellspacing=0><TR  align=center><TD width=55 align=center></td><TD width=88 style='background: #ffc; font-size:150%' align=center><SPAN class=oohfancy>Totaux</SPAN></td>";
   for(i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
         
            str += "<TD width=81><SPAN class=oohfancy>"+ Cities.cities[i].name.substring(0,10) +"</SPAN></td>";
          
   }
   rows = [];
   var now = unixTime();
   rows[0] = [];
   for(i=0; i<Cities.numCities; i++) {
          cityID = 'city'+ Cities.cities[i].id;
          rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
        }
        for (r=1; r<6; r++){
          rows[r] = [];
          for(i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
            if (r==5)
             rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
            else
             rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
            
          }
         
      }
      str += _row ('<img height=18 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/aetherstone_30.png>', rows[5], false, 0);
      str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/3.jpg title="Crafting"></b></td><td>&nbsp;</td>';
                for(i=0; i<Cities.numCities; i++) {
                 var totTime = 0;
                 if (Seed.queue_craft["city" + Cities.cities[i].id].length > 0) {
                  var q=Seed.queue_craft["city" + Cities.cities[i].id][0];
                  var totTime = 0;
                  totTime = q.craftingEtaUnixTime - now;
                  if (totTime < 0)
                    totTime = 0;
                  if (getCityBuilding(Cities.cities[i].id,20).count>0 && totTime == 0)
                    affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                  else
                    affuichage = timestr(totTime);
                  
                  str +="<td><span onclick='BOCrafting("+Cities.cities[i].id+");'>"+ affuichage + "</span></td>";  
           
                 } else {
                 affuichage = timestr(totTime);
                 if (getCityBuilding(Cities.cities[i].id,20).count>0)
                    affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                    
                 str +="<td><span onclick='BOCrafting("+Cities.cities[i].id+");'>"+affuichage+"</span></td>";
                 }
                }    
             str +="</tr>";    
             
         ById("BOCraftStat").innerHTML=str;
         t.timerStat = setTimeout(function() { t.updateStat(); }, 2000);
         
         
  },
  updateCraftnb : function() {
   var t = Tabs.AutoCraft;
   for(var h in t.craftinfo) {
     if (document.getElementById("BOCraft_nb_" +h)) document.getElementById("BOCraft_nb_"+h).value=parseIntNan(TrainOptions.CraftingNb[h]) ;
   }
  },
  saveCraftState : function() {
   var t = Tabs.AutoCraft;
   TrainOptions.CraftingRunning =  t.crafting.running;
   for(var h in t.craftinfo) {
       if (ById("BOCraft_nb_" +h)) TrainOptions.CraftingNb[h] = parseIntNan(ById("BOCraft_nb_"+h).value);
   }
   saveTrainingOptions();
  },
  toggleStateRunning: function(obj){
  	var t = Tabs.AutoCraft;
  	
  	obj = ById('pbCraftRunning');
          if (t.crafting.running == true) {
              t.crafting.running = false;
              t.saveCraftState();
              if (obj) obj.value = "Auto Craft = OFF";
              clearInterval(t.timer);
  	      updatebotbutton('Craft - OFF', 'bocrafttab');
          }
          else {
              t.crafting.running = true;
              t.saveCraftState();
              if (obj) obj.value = "Auto Craft = ON";
              t.timer=setInterval(t.Start,parseInt(t.toutles*1000));
              t.Start();
  	      updatebotbutton('Craft - ON', 'bocrafttab');
          }
          t.updateCraftnb();
    },
    Start: function() {
     var t = Tabs.AutoCraft;
     if(!TrainOptions.CraftingRunning) {
      clearInterval(t.timer);
      return;
     }
     if (t.numcity<Cities.numCities-1) {
           t.numcity++;
         } else {
          t.numcity=0; 
     }
     var c=t.numcity;
     var cityId=Cities.cities[c].id;
     
     var ret=getCityBuilding(cityId,20).count;
     if (ret==0) {
       t.Start();
       return;
     }
     if (parseInt(Seed.resources["city" + cityId]['rec5'][0])<5000) 
            return;
     var tableau = [];
     for(var d in TrainOptions.CraftingNb) {
      
       if (parseInt(TrainOptions.CraftingNb[d])>0) {
 				tableau.push (d);
     
           }
     }
 
     if (tableau.length==0) {
      t.crafting.running = false;
     
      obj = ById('pbCraftRunning');
      if (obj) obj.value = "Auto Craft = OFF";
      setTimeout(function(){updatebotbutton("Craft - OFF", 'bocrafttab');},200);
      
      t.saveCraftState();
      clearInterval(t.timer);
      return;
     
     }
  
     var itemId = tableau[Math.floor(Math.random()*tableau.length)];
     var recipeId = t.craftinfo[itemId].recipe_id;
     var category = t.craftinfo[itemId].category;
     
     
     var i=Seed.queue_craft["city"+cityId];
     if(i.length>0) {
          var q=i[0];
     	  var totTime = 0;
     	  var now = unixTime();
          totTime = q.craftingEtaUnixTime - now;
          if (totTime > 0) {
           return;
          }
     } 
     t.CraftingItem(cityId,  itemId, recipeId, category);
    },
    CraftingItem: function (currentcity, itemId, recipeId,category) {
      var t = Tabs.AutoCraft;
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
          params.action="craft";
          params.ctrl="Crafting";
          params.cityId=currentcity;
          params.insurance=false;
     	  params.itemId=itemId;
     	  params.recipeId=recipeId;
     	  params.categoryId=category;
      new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, { method: "post", parameters: params,loading: true,
          onSuccess: function (transport) {
              var o=eval("("+transport.responseText+")");
              if(o.ok===true){
               if (o.status=="error") {

               } else if(o.status=="failure"){
       	        setTimeout(function() {
    	         t.CraftingItem(currentcity,  itemId, recipeId);
    	        }, 5000);
     	       } else if (o.status=="success"){
      	        TrainOptions.CraftingNb[itemId] =  TrainOptions.CraftingNb[itemId] -1;
     	        saveTrainingOptions();
     	        t.updateCraftnb();
       		if(!Seed.queue_craft["city"+currentcity]) {
    		 Seed.queue_craft["city"+currentcity]=[];
    		}
         	var n={};
         	n.recipeId=recipeId;
         	n.craftingUnixTime=o.time.startTime;
         	n.craftingEtaUnixTime=o.time.endTime;
         	n.craftingId=o.craftingId;
         	n.categoryId=null;
         	n.recipeIndex=null;
         	unsafeWindow.seed.queue_craft["city"+currentcity].push(n);
         	t.Start()
               }
              }
            },
            onFailure: function () {    }
       });
 },
    show : function (){
        var t = Tabs.AutoCraft;
        clearTimeout(t.timerStat);
        t.updateStat();
    },
    hide: function(){
          var t = Tabs.AutoCraft;
          clearTimeout(t.timerStat);
      },
      onUnload: function(){
          var t = Tabs.AutoCraft;
      t.saveCraftState();
    },
};


/*********************************** Options  ***********************************/
Tabs.Options = {
  tabOrder: 30,
  tabLabel: 'Options',
  cont : null,
  state : null,
  fixAvailable : {},
  soundRepeatTimer : null,
  soundStopTimer : null,
  secondTimer : null,
  soundPlaying : false,
  show : function (){
    var t = Tabs.Options;
  },

  stopSoundAlerts : function (){
    var t = Tabs.Options;
    obj = ById('boSoundStop');
	t.mss.stop (1);
    clearTimeout (t.soundStopTimer);
    clearTimeout (t.soundRepeatTimer);
    ById('boSoundStop').disabled = true;
    Options.alertSound.alarmActive = false;
    Options.alertSound.expireTime = 0;
    	setTimeout(function() {
             	   if (ById('botowertab'))
             	     ById('botowertab').style.display="none";
         	},2000);
  },
  e_soundFileLoaded : function (chan, isError){
      if (chan != 1)
        return;
      if (isError)  
        ById('boLoadStat').innerHTML = 'Erreur !';
      else
        ById('boLoadStat').innerHTML = 'Charg&eacute;';
    },  
  playSound : function (doRepeats){
      var t = Tabs.Options;
      ById('boSoundStop').disabled = false;
      clearTimeout (t.soundStopTimer);
      clearTimeout (t.soundRepeatTimer);
      t.mss.play(1, 0);
      t.soundStopTimer = setTimeout (function(){t.mss.stop(1); t.e_soundFinished(1)}, Options.alertSound.playLength*1000);
      if (doRepeats && Options.alertSound.repeat)
        t.soundRepeatTimer = setTimeout (function (){t.playSound(true)}, Options.alertSound.repeatDelay*60000);
      else
        Options.alertSound.alarmActive = false;
    },
   e_soundFinished : function (chan){ 
    var t = Tabs.Options;
    if (chan != 1)
      return;
    if (!Options.alertSound.alarmActive){
      ById('boSoundStop').disabled = true;
    }
  },        
  soundTheAlert : function (m){
      var t = Tabs.Options;
      
      var totTroops = 0;
      for (k in m.unts) {
      	var uid = parseInt(k.substr(1));
      	totTroops += m.unts[k];
      }
      
      
      Options.alertSound.alarmActive = true;
      t.playSound(true);
  },
  

  hide : function (){
    var t = Tabs.Options;
  },
  togOpt : function (checkboxId, optionName, callEnable, callIsAvailable){
    var t = Tabs.Options;
    var checkbox = ById(checkboxId);
    
    if (callIsAvailable && callIsAvailable()==false){
      checkbox.disabled = true;
      return;
    }
    if (Options[optionName])
      checkbox.checked = true;
    checkbox.addEventListener ('change', new eventToggle(checkboxId, optionName, callEnable).handler, false);
    function eventToggle (checkboxId, optionName, callOnChange){
      this.handler = handler;
      var optName = optionName;
      var callback = callOnChange;
      function handler(event){
        Options[optionName] = this.checked;
        saveOptions();
        if (callback != null)
          callback (this.checked);
      }
    }
  },


   init : function (div){
    var t = Tabs.Options;
    t.cont = div;
    if (Options.DeleteTimerMinute===undefined) Options.DeleteTimerMinute=5;
    if (Options.NewTabURL==undefined) Options.NewTabURL=sitesupport;
       setTimeout(function() {
        AddTowerTab(' <blink> >> ! << </blink> ', t.stopSoundAlerts, 'botowertab');
       }, 1000);
        
        var chat = ById('kocmain_bottom').childNodes[1];
        if (chat) {
           var channel_input = nHtml.FindByXPath(chat,".//div[contains(@class,'mod_comm_forum')]");
           var ab = document.createElement('a');
           ab.className="mod_comm_set";
           channel_input.appendChild(ab);
           ab.innerHTML="Smiley";
           ab.addEventListener ('click', function() {
            t.EmoHelp();
           },false);
           
      } try {      
        m = '<DIV style="height:'+(Options.HauteurBoite-25)+'px; max-height:'+(Options.HauteurBoite-25)+'px; overflow-y:auto">\
          <DIV class=boStat>Bienvenue sur la Boite &agrave; Outils Version '+Version+' - <input type=button value="?" id=boaideoptions class=boAide></div>\
          <TABLE class=ptTab>\
		  	<TD></TD><TD><B>'+culang.pack+'</B>:\
		<select id=pbLang '+(LangOptions.culang==0?'DISABLED':'')+'/><option value=0 >-- '+culang.select+' --</option>';
		for (var i in LangOptions.langpacks) {
		if(i == LangOptions.culang)
			m += '<option value="'+i+'" selected="selected">'+i+'</option>'; // Load Previous langpack Selection
		else
			 m += '<option value="'+i+'">'+i+'</option>';
		};
		m += '</select><b> '+culang.mainImportant+'</b>: <span class=boldRed>'+LangpackVersion+'</span> <INPUT id=pbupdatelanglist type=submit value='+langpack.updatelangbtn+'>\
		<b><BR><span class=boldRed><u>'+culang.mainImportant+'</u>:</span> '+culang.mainImportant+'</b></td>\
          <TR><TD colspan=4><B><u>Configuration :</u></b></td></tr>\
          <TR><TD width=5%><INPUT id=ptAllowWinMove type=checkbox /></td><TD width=45%>D&eacute;placement de la fen&ecirc;tre.</td>\
          <TD width=5%><INPUT id=ptAllowTransparent type=checkbox /></td><TD width=45%>Transparence des fen&ecirc;tres (10%)</td></tr>\
          <TR><TD><INPUT id=pbEveryEnable type=checkbox /></td><TD>Actualiser KOC toutes les <INPUT id=pbeverymins type=text size=2 maxlength=3 \> minutes</td>\
          <TD><INPUT id=ptEnableReduireUnit type=checkbox /></td><TD>R&eacute;duire l\'affichage des ressources dans r&eacute;sum&eacute;</td></tr>\
          <TR><TD><INPUT id=boWideOpt type=checkbox '+ (GlobalOptions.pbWideScreen?'CHECKED ':'') +'/></td><TD>Activer le plein &eacute;cran : '+ htmlSelector({normal:'Normal', wide:'Widescreen', ultra:'Ultra'},GlobalOptions.pbWideScreenStyle,'id=BOselectScreenMode') +'</td>\
	  <TD><INPUT id=pbChatREnable type=checkbox /></td><TD>Mettre le Chat sur la droite (besoin du plein &eacute;cran)</td>\
	  <TR><td></td><TD colspan=3>Hauteur de la boite : <INPUT id="optHauteurBoite" type=text size=4 value="'+ Options.HauteurBoite +'">px (700 par defaut)</td></tr>\
	  <TR><TD width=5%><INPUT id=pbWMapEnable type=checkbox /></td><TD width=45%>Utiliser la carte large (besoin du plein &eacute;cran)</td><TD><INPUT id=MapExtra type=checkbox /></td><TD>Informations compl&eacute;mentaires sur la carte. </td></tr>\
	  <TR><TD><INPUT id=BOgmtClock type=checkbox '+ (Options.gmtClock?'CHECKED ':'') +'/></td><TD>Modifier l\'horloge du jeu en GMT</td><TD><INPUT id=BOchecktournoi type=checkbox '+ (Options.checktournoi?'CHECKED ':'') +'/></td><TD>Rechercher l\'arriv&eacute; d\'un tournoi toute les 10 minutes.</td></tr>\
	  <TR><TD><INPUT id=boWatchEnable type=checkbox '+ (GlobalOptions.pbWatchdog?'CHECKED ':'') +'/></td><TD>Actualiser si KOC n\'est pas charg&eacute; pendant 1 minute</td></tr>\
	  <TR><TD><INPUT id=PubReq type=checkbox '+ (GlobalOptions.autoPublishGamePopups?'CHECKED ':'') +'/></td><TD colspan=3>Publier automatiquement sur Facebook (Tout Domaine - suivant le param&eacute;trage Facebook)</td>\
	  <TR><TD><INPUT id=BONewTab type=checkbox '+ (Options.NewTab?'CHECKED ':'') +'/></td><TD colspan=3>Activer l\'onglet personnalisable : URL : <input type=text size=20 value="'+Options.NewTabURL+'" id=BONewTabURL>&nbsp Nom : <input type=text size=10 maxlength=12 id=BONewTabName value="'+Options.NewTabName+'"></td>\
	  <TR><TD colspan=4><P><B><u>Configuration du r&eacute;sum&eacute; :</u></b></td></tr>\
          <TR><TD><INPUT id=togShowTroops  type=checkbox /></td><TD>Montrer les troupes.</td><TD><INPUT id=togShowDefense  type=checkbox /></td><TD>Montrer les d&eacutefenses.</td></tr>\
          <TR><TD><INPUT id=togShowRes type=checkbox /></td><TD>Montrer le stock de ressources.</td><TD><INPUT id=togShowPop type=checkbox /></td><TD>Montrer les informations sur la population.</td></tr>\
          <TR><TD>&nbsp;&nbsp;<INPUT id=togShowProduction type=checkbox /></td><TD>Montrer la production de ressources.</td></tr>\
          <TR><TD><INPUT id=togincludeMarching type=checkbox /></td><TD>Inclure les troupes et ressources marchants.</td><TD><INPUT id=togEnableFormation type=checkbox /></td><TD>Afficher les troupes en cours de formation.</td></tr>\
          <TR><TD><INPUT id=ptEnableFoodWarn type=checkbox /></td><TD colspan=3>Montrer \'Autonomie\' en rouge si la production de nourriture est en n&eacute;gatif et inf&eacute;rieure &agrave; <INPUT id=optFoodHours type=text size=3 value="'+ Options.foodWarnHours +'"> heures</td></tr>\
 </table><TABLE class=ptTab><TR><TD colspan=2><P><B><u>Fonctionnalit&eacute;s suppl&eacute;mentaires :</u></b></td></tr><TR><TD colspan=2><B>Le Chat :</b></td></tr>\
          <TR><TD><INPUT id=ptEnableFoodWarnTchat type=checkbox /></td><TD>Activer le post automatique sur tchat alliance en cas d\'autonomie en rouge</td></tr>\
          <TR><TD><INPUT id=HelReq type=checkbox /></td><TD>Aider automatiquement pour les constructions/recherches des autres membres</td></tr>\
	  <TR><TD><INPUT id=DelReq type=checkbox /></td><TD>Supprimer les demandes divers (aides) du Chat Alliance</td></tr>\
	  <TR><TD><INPUT id=DelRules type=checkbox /></td><TD>Supprimer les r&egrave;gles du Chat</td></tr>\
   	  <TR><TD><INPUT id=togChatStuff type=checkbox /></td><TD>Activer les am&eacute;liorations du TChat  (coords cliquable, couleurs diverses, cliquer sur avatar pour chuchoter)</td></tr>\
          <TR><TD>&nbsp;&nbsp;&nbsp;<INPUT id=togWhisperOn type=checkbox /></td><TD>Audio sur le chuchotement <INPUT id=togURL1 size=40 type=textbox value="'+ Options.URLson1 +'" /><input type=button value="Def" id="BODefURL1"></td></tr>\
          <TR><TD>&nbsp;&nbsp;&nbsp;<INPUT id=togEclaireurOn type=checkbox /></td><TD>Audio sur une alerte ECLAIREUR <INPUT id=togURL4 size=40 type=textbox value="'+ Options.URLson4 +'" /><input type=button value="Def" id="BODefURL4"</td></tr>\
     	  <TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatEcl style="background-color:'+Colors.ChatEcl+'" type=text size=7 maxlength=7 value="'+Colors.ChatEcl+'"> Couleur Chat - Eclaireur Tower Alert</td></tr>\
     	  <TR><TD>&nbsp;&nbsp;&nbsp;<INPUT id=togAttaqueOn type=checkbox /></td><TD>Audio sur une alerte ATTAQUE <INPUT id=togURL2 size=40 type=textbox value="'+ Options.URLson2 +'" /><input type=button value="Def" id="BODefURL2"</td></tr>\
          <TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatAtt style="background-color:'+Colors.ChatAtt+'" type=text size=7 maxlength=7 value="'+Colors.ChatAtt+'"> Couleur Chat - Attaque Tower Alert</td></tr>\
          <TR><TD><INPUT id=BOSmiley type=checkbox /></td><TD>Afficher des Emoticones <INPUT id=EmoHelp type=submit value="Aide"></td></tr>\
	  <TR><TD><INPUT id=BOChatLeader type=checkbox /></td><TD>Afficher les couleurs sur les Leaders - <a target=_blank href="http://bastnt.free.fr/palette.html">Aide pour trouver les couleurs</a></td></tr>\
	  <TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatC style="background-color:'+Colors.ChatChancy+'" type=text size=7 maxlength=7 value="'+Colors.ChatChancy+'"> Couleur Chat - Chancelier</td></tr>\
	  <TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatVC style="background-color:'+Colors.ChatVC+'" type=text size=7 maxlength=7 value="'+Colors.ChatVC+'"> Couleur Chat - Vice-Chancelier</td></tr>\
	  <TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatLeaders style="background-color:'+Colors.ChatLeaders+'" type=text size=7 maxlength=7 value="'+Colors.ChatLeaders+'"> Couleur Chat - Officier</td></tr>\
	  <TR><TD>&nbsp;</td><TD><INPUT id=togChatGlo style="background-color:'+Colors.ChatGlo+'" type=text size=7 maxlength=7 value="'+Colors.ChatGlo+'"> Couleur de fond du chat global</td></tr>\
	  <TR><TD><INPUT id=user_icon type=checkbox /></td><TD>Changer son avatar sur le chat <INPUT id=togURL3 size=30 type=textbox value="'+Options.URLicon+'" /><input type=button value="Def" id="BODefURL3"/> (Taille image requis : 25x25)<br><i>Visible que par vous</i></td></tr>\
	  <TR><TD colspan=2><B>Les Rapports de KoC :</b></td></tr>\
          <TR><TD><INPUT id=togAllRpts type=checkbox /></td><TD>Am&eacute;liorer les rapports de l\'alliance.</td></tr>\
          <TR><TD><INPUT id=togAllMembers type=checkbox /></td><TD>Am&eacute;liorer la visu des membres de l\'alliance.</td></tr>\
          <TR><TD><INPUT id=togAtkDelete type=checkbox DISABLED/></td><TD>Activer le bouton Annuler sur un rapport</span></td></tr>\
          <TR><TD></td><td>Supprimer automatiquement les rapports : <input type=button id=bodeletenow value="Maintenant"></tr>\
          <TR><td></td><TD colspan=1><INPUT id=delete4toggle type=checkbox /> eclaireur (de vous)&nbsp; <INPUT id=deletetoggle type=checkbox /> barbare/transport (de vous)&nbsp;<INPUT id=deletes0toggle type=checkbox /> transport (vers vous)&nbsp;<INPUT id=deletes1toggle type=checkbox /> TS&nbsp;<INPUT id=deletes2toggle type=checkbox /> '+unsafeWindow.g_js_strings.commonstr.darkForest+'&nbsp;<INPUT id=deletes3toggle type=checkbox /> renforts recus</td></tr>\
          <TR><TD></td><td>D&eacute;lai de recherche dans les rapports : <input type=text size=3 id=BOdeletetimer value="' + Options.DeleteTimerMinute + '"> Minutes</td></tr>\
	  <TR><TD colspan=2><B>Divers :</b></td></tr>';
          var citySelect = '<SELECT id=pcalertHQ name=pcalertHQ><option value="">.....</option>';
 	  var couleur="";
 	
	     for (var c=0; c<Cities.numCities; c++) {
	       aCity = Cities.cities[c].id;
	       aVisuCity = Cities.cities[c].name + ' '+Cities.cities[c].x + ','+ Cities.cities[c].y+' ';
	       citySelect += '<option value=\''+ aCity +'\' '+ (Options.alertConfig.hq==aCity?'SELECTED ':'') +'>'+aVisuCity+'</option>';
	 
	     }
	  citySelect += '</select>';
	  if (Options.alertConfig.minTroops2==undefined) Options.alertConfig.minTroops2=1;
	  m +='<TR><td></td><TD align=left>Ma ville forte ( QG ) :&nbsp;'+ citySelect +'</td></tr>';
          m +='<TR><TD><INPUT id=togSelQG type=checkbox /></td><TD>S&eacute;lectionner automatiquement cette ville &agrave; l\'ouverture du jeu.</td></tr>\
  <TR><TD><INPUT id=pbGoldEnable type=checkbox /></td><TD>Collecte automatique de l\'or quand le bonheur est sup&eacute;rieur &agrave; <INPUT id=pbgoldLimit type=text size=2 maxlength=3>%</td></tr>\
          <TR><TD><INPUT id=togAttackPicker type=checkbox /></td><TD>Activer la s&eacute;lection rapide des villes dans la boite d\'attaque (renforcer, reassigner et transport)</span></td></tr>\
          <TR><TD><INPUT id=togEnhanceMsging type=checkbox /></td><TD>Am&eacute;liorer la gestion des messages (Champs CC)</td></tr>\
          <TR><TD colspan=2><B>Corrections de bugs KofC :</b></td></tr>\
          <TR><TD><INPUT id=togKnightSelect type=checkbox /></td><TD>D&eacute;sactiver automatiquement la s&eacute;lection d\'un chevalier (Eclairer, transport ou reassigner)</td></tr>\
          <TR><TD><INPUT id=togCoordBox type=checkbox /></td><TD>Garder la fen&ecirc;tre des favoris toujours devant de l\'activit&eacute des troupes</td></tr>\
          <TR style="display:none"><TD><INPUT id=togMapDistFix type=checkbox /></td><TD>Corriger la carte pour montrer la distance suivant la bonne ville s&eacute;lectionn&eacute;e</td></tr>';
     m +='<TR><TD colspan=2><BR><B><u>Configuration de TowerAlert :</u></b></td></tr>\
	  <TR><TD><INPUT id=pcalertEnable type=checkbox '+ (Options.alertConfig.aChat?'CHECKED ':'') +'/></td><TD>Activer la TowerAlert</td></tr>\
          <TR><TD><INPUT id=boSoundEnable type=checkbox '+ (Options.alertSound.enabled?'CHECKED ':'') +'/></td><TD>Activer la lecture d\'un son sur une attaque/eclairage entrante</td></tr>\
	  <TR><TD></td><TD><DIV id=boLoadingSwf>Chargement du SWF player</div><DIV style="display:none" id=boSoundOpts><TABLE cellpadding=0 cellspacing=0>\
	  <TR><TD align=right>Fichier son : &nbsp; </td><TD><INPUT id=bosoundFile type=text size=55 maxlength=160 value="'+ Options.alertSound.soundUrl +'" \>\
	   &nbsp; </td><TD><INPUT id=boSoundLoad type=submit value="Charger"><INPUT id=boSoundDefault type=submit value=Default></td></tr>\
	  <TR><TD align=right>Volume : &nbsp; </td><TD><TABLE cellpadding=0 cellspacing=0 class=pbTab><TR valign=middle><TD><SPAN id=boVolSlider></span></td><TD width=15></td><TD align=right id=boVolOut>0</td></td></table></td><TD align=center><SPAN id=boLoadStat>xx</span></td></tr>\
	  <TR><TD align=right><INPUT id=boSoundRepeat type=checkbox '+ (Options.alertSound.repeat?'CHECKED ':'') +'/></td><TD>Repeter <INPUT id=boSoundEvery type=text size=2 maxlength=5 value="'+ Options.alertSound.repeatDelay +'"> minutes</td></tr>\
	  <TR><TD></td><TD>Jouer pendant <INPUT id=boSoundLength type=text size=3 maxlength=5 value="'+ Options.alertSound.playLength +'"> secondes</td></tr>\
	  <TR><TD></td><TD><INPUT type=submit value="Tester" id=boPlayNow> &nbsp; <INPUT id=boSoundStop type=submit value="Stop Sound Alert"></td></tr></table></div></td></tr>\
          <TR><TD></td><TD><TABLE cellpadding=0 cellspacing=0 class=ptTab>';
          m +='	<TR><TD align=right>Poster une alerte : </td><TD>&nbsp;<INPUT id=pcalertSendToAlly type=checkbox '+ (Options.alertConfig.sendtoAlly?'CHECKED ':'') +' /> sur tchat alliance et/ou <INPUT id=pcalertSendAsWhisper type=checkbox '+ (Options.alertConfig.sendasWhisper?'CHECKED ':'') +' /> en chuchotement &agrave; soi m&ecirc;me</td></tr>\
                <TR><TD align=right>Message Perso : &nbsp; </td><TD><INPUT id=pcalertPrefix type=text size=55 maxlength=120 value="'+ Options.alertConfig.aPrefix +'" \></td></tr>\
		<TR><TD align=right>Alerter : &nbsp; </td><TD><INPUT id=pcalertWild type=checkbox '+ (Options.alertConfig.wilds?'CHECKED ':'') +'/> TS&nbsp; - <INPUT id=pcalertScout type=checkbox '+ (Options.alertConfig.scouting?'CHECKED ':'') +'/> &eacute;claireur</td></tr>\
		<TR><TD align=right>Minimum de troupes :<br><i>(Alertes sur le chat)</i></td><TD><INPUT id=pcalertTroops type=text size=7 value="'+ Options.alertConfig.minTroops +'" \> sur QG - <INPUT id=pcalertTroops2 type=text size=7 value="'+ Options.alertConfig.minTroops2 +'" \> sur villes secondaires&nbsp; &nbsp; <span id=pcalerterr></span></td></tr>\
		<TR><TD align=right>Afficher si d&eacute;fend ou pas : &nbsp; </td><TD><INPUT id=pbalertDefend type=checkbox '+ (Options.alertConfig.defence?'CHECKED ':'') +' \> &nbsp; &nbsp; </td></tr>\
		<TR><TD align=right>Montrer mon empennage : &nbsp; </td><TD><INPUT id=pcalertEmpennage type=checkbox '+ (Options.alertConfig.empennage?'CHECKED ':'') +'/></td></tr>\
		<TR><TD align=right>Montrer le niveau de mon mar&eacute;chal (Sans boost) : &nbsp; </td><TD><INPUT id=pcalertMarechal type=checkbox '+ (Options.alertConfig.marechal?'CHECKED ':'') +'/></td></tr>\
		<TR><TD align=right>Montrer ma peau (D&eacute;fense renforc&eacute;e) : &nbsp; </td><TD><INPUT id=pcalertdefBoost type=checkbox '+ (Options.alertConfig.defBoost?'CHECKED ':'') +'/></td></tr>\
		<TR><TD align=right>Montrer troupes dans ambassade : &nbsp; </td><TD><INPUT id=pcalertEmbassy type=checkbox '+ (Options.alertConfig.embassy?'CHECKED ':'') +'/></td></tr>\
		<TR><TD align=right>Afficher : &nbsp; </td><TD><INPUT id=pcalertMytroops type=checkbox '+ (Options.alertConfig.mytroops?'CHECKED ':'') +'/>mes troupes - <INPUT id=pcalertDefense type=checkbox '+ (Options.alertConfig.defense?'CHECKED ':'') +' /> mes d&eacute;fenses </td></tr>\
		<TR><TD align=right>Montrer ma consommation de nourriture : &nbsp; </td><TD><INPUT id=pcalertFood type=checkbox '+ (Options.alertConfig.food?'CHECKED ':'') +' /></td></tr>\
		<TR><TD align=right>D&eacute;activer l\'affichage du QG (ville forte) : </td><td><INPUT id=pcalertQG type=checkbox '+ (Options.alertConfig.MonQG?'CHECKED ':'') +' /></td></tr>\
		<TR><TD align=right>Stopper  sur attaque entrante : </td><td><INPUT id=BOalertraid type=checkbox '+ (Options.alertConfig.raid?'CHECKED':'') +'/> RAID - <INPUT id=BOalertappro type=checkbox '+ (Options.alertConfig.appro?'CHECKED':'') +'/> APPRO - <INPUT id=BOalertautofo type=checkbox '+ (Options.alertConfig.autofo?'CHECKED':'') +'/> AUTOFO - <INPUT id=BOalertautots type=checkbox '+ (Options.alertConfig.autots?'CHECKED':'') +'/> AUTOTS</td></tr>\
		<TR><TD align=right>Envoyer un email : &nbsp; </td><TD><INPUT id=pcalertSendEmail type=checkbox '+ (Options.alertConfig.sendEmail?'CHECKED ':'') +' /> email : &nbsp; <INPUT id=pcalertEmailAddress type=text size=36 value="'+ Options.alertConfig.emailAddress +'" \> &nbsp; &nbsp;</td></tr>\
		<TR style="display:none"><TD align=right>My token : &nbsp; </td><TD><INPUT id=pcalertToken type=text size=36 value="'+ Options.alertConfig.token +'" \> &nbsp; &nbsp;</td></tr>';
          m +="</table></table><BR><BR><HR><font size=2><br><SPAN class=oohfancy><font size=6>BeWorld</font></span><br>Vous pouvez m\'envoyer un don de GEMS (me contacter avant) pour supporter la boite.<br><bR>Merci KOC Power Bot et KOC Power Tools - KoC Scripters<br>Merci &eacute;galement &agrave; Conik et aux personnes qui ont apport&eacute;es leurs contributions.<br><br>"+strButton20('Reinitialiser TOUTES Les options', 'id=BOResetALL')+" " + strButton20('Reinitialiser Couleurs', 'id=ResetALL') +"<br><br></div>";

    t.cont.innerHTML = m;
    
    ById('EmoHelp').addEventListener('click', function(){t.EmoHelp();} , false);
    ById('boaideoptions').addEventListener('click', function(){
    	 window.open(sitesupport+"?page=aide_options");
    	} , false);
	
    ById('bodeletenow').addEventListener('click', function(){ DeleteReports.startdeletereports(); }, false);
    t.togOpt ('togAtkDelete', 'reportDeleteButton');
    t.togOpt ('BONewTab', 'NewTab');
    ById('BONewTabURL').addEventListener ('change', function () {
    	   Options.NewTabURL = ById('BONewTabURL').value;
               saveOptions();
	}, false);
	ById('BONewTabName').addEventListener ('change', function () {
	    	   Options.NewTabName = ById('BONewTabName').value;
	               saveOptions();
	}, false);
    ById('togChatLeaders').addEventListener('change', function(){
      Colors.ChatLeaders = ById('togChatLeaders').value;
      ById('togChatLeaders').style.backgroundColor=ById('togChatLeaders').value;
    }, false);
     ById('togChatVC').addEventListener('change', function(){
          Colors.ChatVC = ById('togChatVC').value;
          ById('togChatVC').style.backgroundColor=ById('togChatVC').value;
    }, false);
     ById('togChatC').addEventListener('change', function(){
          Colors.ChatChancy = ById('togChatC').value;
          ById('togChatC').style.backgroundColor=ById('togChatC').value;
    }, false);
     ById('togChatAtt').addEventListener('change', function(){
          Colors.ChatAtt = ById('togChatAtt').value;
          ById('togChatAtt').style.backgroundColor=ById('togChatAtt').value;
    }, false);
    ById('togChatEcl').addEventListener('change', function(){
              Colors.ChatEcl = ById('togChatEcl').value;
              ById('togChatEcl').style.backgroundColor=ById('togChatEcl').value;
    }, false);
     ById('togChatGlo').addEventListener('change', function(){
              Colors.ChatGlo = ById('togChatGlo').value;
              ById('togChatGlo').style.backgroundColor=ById('togChatGlo').value;
    }, false);
    if (couleur!="") {
     ById('pcalertHQ').style.background="red";
    }
    ById('boWideOpt').addEventListener ('change', t.e_wideChanged, false);
    ById('boWatchEnable').addEventListener ('change', t.e_watchChanged, false);
    ById('PubReq').addEventListener ('change', function(){
          		GlobalOptions.autoPublishGamePopups = ById('PubReq').checked;
    			GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
    },false);
    ById('BOResetALL').addEventListener ('click', function(){
    	  		var serverID = getServerId();
    	  		RemoveList = (GM_listValues());
    	  		for (i=0;i<RemoveList.length;i++){
    	  			GM_deleteValue(RemoveList[i]);
    	  		}
    	  		ResetAll=true;
    	  		reloadKOC();
    },false);
    ById('ResetALL').addEventListener ('click', function(){
          		RemoveList = (GM_listValues());
          		for (i=0;i<RemoveList.length;i++){
          			if (RemoveList[i] == "Colors") GM_deleteValue(RemoveList[i]);
          		}
          		ResetColors=true;
          		reloadKOC();
      },false);
	  		ById('pbupdatelanglist').addEventListener ('click', function () {
			GM_xmlhttpRequest({
			method: 'GET',
			url: 'http://koc-power-beta.googlecode.com/svn/trunk/langpacks/',
			headers: {
			'Accept': 'text/javascript',
		},
    onload: function(responseDetails) {
		var exp = /(\w\w)(?=.js<\/a>)/gim;
		var str = responseDetails.responseText;
		var str = str.match(exp);
		for (i in str) {
			if (str.length > i) {
				if(str[i]=="SR") continue;// exclude string resource file
				LangOptions.langpacks[str[i]] = true;
			};
		}
		saveLangOptions();
    }
});
	  }, false);
	  ById('pbLang').addEventListener ('change', function () {
				LangOptions.culang = this.options[this.selectedIndex].text ;
				saveLangOptions();
	  }, false);
    ById('BOselectScreenMode').addEventListener ('change', function(){
	      		GlobalOptions.pbWideScreenStyle = ById('BOselectScreenMode').value;
	      		GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
    },false);	  
    t.mss = new CmatSimpleSound("http://beworld.perso.sfr.fr/bao/alarmplayer.swf", null, {height:0, width:0}, t.e_swfLoaded, 'debug=n');
    t.mss.swfDebug = function (m){ logit ('SWF: '+ m)};
    t.mss.swfPlayComplete = t.e_soundFinished;
    t.mss.swfLoadComplete = t.e_soundFileLoaded;
    unsafeWindow.matSimpleSound01 = t.mss;

    t.volSlider = new SliderBar (ById('boVolSlider'), 200, 21, 0);
    t.volSlider.setChangeListener(t.e_volChanged);
    ById('boPlayNow').addEventListener ('click', function (){t.playSound(false)}, false);
    ById('boSoundStop').addEventListener ('click', t.stopSoundAlerts, false);
   
    ById('boSoundRepeat').addEventListener ('change', function (e){Options.alertSound.repeat = e.target.checked}, false);
    ById('boSoundEvery').addEventListener ('change', function (e){Options.alertSound.repeatDelay = e.target.value}, false);
    ById('boSoundLength').addEventListener ('change', function (e){Options.alertSound.playLength = e.target.value}, false);
    ById('boSoundEnable').addEventListener ('change', function (e){Options.alertSound.enabled = e.target.checked}, false);

    ById('boSoundStop').disabled = true;
    ById('bosoundFile').addEventListener ('change', function (){
           Options.alertSound.soundUrl = ById('bosoundFile').value;
           t.loadUrl (Options.alertSound.soundUrl);
    }, false);
    ById('boSoundDefault').addEventListener ('click', function (){
           ById('bosoundFile').value = DEFAULT_ALERT_SOUND_URL;
           Options.alertSound.soundUrl = DEFAULT_ALERT_SOUND_URL;
           t.loadUrl (DEFAULT_ALERT_SOUND_URL);
    }, false);
    t.togOpt ('BOgmtClock', 'gmtClock', gmtClock.setEnable);
    t.togOpt ('DelRules', 'ChatRules');
     t.togOpt ('BOchecktournoi','checktournoi');
    t.togOpt ('togSelQG', 'SelQG');
    t.togOpt ('BOSmiley', 'Smiley');
    t.togOpt ('BOChatLeader', 'ChatLearder');
    t.togOpt ('togShowTroops', 'showTroops');
    t.togOpt ('togShowPop', 'showPop');
    t.togOpt ('togShowRes', 'showRes');
    t.togOpt ('togShowProduction', 'showProduction');
    t.togOpt ('togincludeMarching', 'includeMarching');
    t.togOpt ('togEnableFormation', 'EnableFormation');
    t.togOpt ('togShowDefense', 'showDefense');
    t.togOpt ('ptEnableFoodWarn', 'enableFoodWarn');
    t.togOpt ('pbGoldEnable', 'pbGoldEnable', CollectGold.setEnable);
    t.changeOpt ('pbgoldLimit', 'pbGoldHappy');
    t.togOpt ('togAllMembers', 'enhanceViewMembers', AllianceReports.enable_viewmembers);
    t.togOpt ('ptEnableFoodWarnTchat', 'enableFoodWarnTchat', FoodAlerts.init);
    t.togOpt ('ptEnableReduireUnit', 'EnableReduireUnit');
    t.togOpt ('ptAllowWinMove', 'ptWinDrag', mainPop.setEnableDrag);
    t.togOpt ('ptAllowTransparent', 'BOTransparence');

    t.togOpt ('togChatStuff', 'chatEnhance', ChatStuff.setEnable, ChatStuff.isAvailable);
    t.togOpt ('togKnightSelect', 'fixKnightSelect', AttackDialog.setEnable, AttackDialog.isKnightSelectAvailable);
    t.togOpt ('togAttackPicker', 'attackCityPicker', AttackDialog.setEnable, AttackDialog.isCityPickerAvailable);
    t.togOpt ('togEnhanceMsging', 'enhanceMsging', messageNav.setEnable, messageNav.isAvailable);
    t.togOpt ('togCoordBox', 'mapCoordsTop', CoordBox.setEnable, CoordBox.isAvailable);
    t.togOpt ('togWhisperOn', 'WhisperOn');
    t.togOpt ('togAttaqueOn', 'AttaqueOn'); t.togOpt ('togEclaireurOn', 'EclaireurOn');  
    t.togOpt ('user_icon', 'icon_chat');
    t.togOpt ('MapExtra', 'MapShowExtra');        
    t.togOpt ('deletetoggle', 'DeleteMsg');
    t.togOpt ('delete4toggle', 'DeleteMsgs4');
    t.togOpt ('deletes0toggle', 'DeleteMsgs0');
	t.togOpt ('deletes1toggle', 'DeleteMsgs1');
        t.togOpt ('deletes2toggle', 'DeleteMsgs2');
        t.togOpt ('deletes3toggle', 'DeleteMsgs3');
        t.togOpt ('HelReq', 'HelpRequest');
        t.togOpt ('DelReq', 'DeleteRequest');    
        t.changeOpt ('pbeverymins', 'pbEveryMins' , RefreshEvery.setTimer);
	t.togOpt ('pbEveryEnable', 'pbEveryEnable', RefreshEvery.setEnable);
	t.togOpt ('pbChatREnable', 'pbChatOnRight', WideScreen.setChatOnRight);
	t.togOpt ('pbWMapEnable', 'pbWideMap', WideScreen.useWideMap);
 	t.togOpt ('togAllRpts', 'enhanceARpts', AllianceReports.enable);
        ById('pcalertEnable').addEventListener ('change', t.e_alertOptChanged, false);
        ById('pbalertDefend').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertPrefix').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertQG').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertScout').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertWild').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertTroops').addEventListener ('change', t.e_alertOptChanged, false);      
	ById('pcalertTroops2').addEventListener ('change', t.e_alertOptChanged, false); 
	ById('pcalertEmbassy').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertEmpennage').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertMarechal').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertdefBoost').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertMytroops').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertFood').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertDefense').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertHQ').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertSendEmail').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertEmailAddress').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertToken').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertSendAsWhisper').addEventListener ('change', t.e_alertOptChanged, false);
	ById('pcalertSendToAlly').addEventListener ('change', t.e_alertOptChanged, false);
	ById('BOalertraid').addEventListener ('change', t.e_alertOptChanged, false);
	ById('BOalertautofo').addEventListener ('change', t.e_alertOptChanged, false);
	ById('BOalertautots').addEventListener ('change', t.e_alertOptChanged, false);
	ById('BOalertappro').addEventListener ('change', t.e_alertOptChanged, false);
	

	ById('BOdeletetimer').addEventListener ('change', function () {
	  if (parseInt(ById('BOdeletetimer').value) < 5) {
	    ById('BOdeletetimer').value=5;
	  }

	  Options.DeleteTimerMinute = ById('BOdeletetimer').value;
	  saveOptions();
	}, false);
	ById('togURL1').addEventListener ('change', function () {
	   Options.URLson1 = ById('togURL1').value;
           saveOptions();
	}, false);
	ById('togURL2').addEventListener ('change', function () {
	    Options.URLson2 = ById('togURL2').value; 
            saveOptions();
	}, false);
	ById('togURL4').addEventListener ('change', function () {
		    Options.URLson4 = ById('togURL4').value; 
	            saveOptions();
	}, false);

	ById('togURL3').addEventListener ('change', function () {
		   Options.URLicon = ById('togURL3').value;
	           saveOptions();
		}, false);
	
	ById("BODefURL3").addEventListener ('click', function () {
			   Options.URLicon = 'http://www.france-lol.fr/francelol.tools/images/ip_points.png';
			   ById('togURL3').value='http://www.france-lol.fr/francelol.tools/images/ip_points.png';
		           saveOptions();
	}, false);
	
	ById("BODefURL1").addEventListener ('click', function () {
	   Options.URLson1 = 'http://www.universal-soundbank.com/mp3/sounds/684.mp3';
	   ById('togURL1').value='http://www.universal-soundbank.com/mp3/sounds/684.mp3';
           saveOptions();
	}, false);
	ById("BODefURL2").addEventListener ('click', function () {
		   Options.URLson2 = 'http://www.universal-soundbank.com/mp3/sounds/217.mp3';
		   ById('togURL2').value='http://www.universal-soundbank.com/mp3/sounds/217.mp3';
	           saveOptions();
	}, false);
	ById("BODefURL4").addEventListener ('click', function () {
			   Options.URLson2 = 'http://www.universal-soundbank.com/mp3/sounds/2376.mp3';
			   ById('togURL4').value='http://www.universal-soundbank.com/mp3/sounds/2376.mp3';
		           saveOptions();
	}, false);
	
	ById('optHauteurBoite').addEventListener ('change', function () {
	     var x = ById('optHauteurBoite').value;
	    if (isNaN(x) || x<600 || x>1000){
	     ById('optHauteurBoite').value = 700; 
	    }
	    Options.HauteurBoite = x;
	    saveOptions();
          }, false);
	
	
        ById('optFoodHours').addEventListener ('change', function () {
            var x = ById('optFoodHours').value; 
            if (isNaN(x) || x<0.01 || x>99999){
              ById('optFoodHours').value = Options.foodWarnHours;
              return;
            }
            Options.foodWarnHours = x; 
            saveOptions();
          }, false);
  
        var checkbox = ById('togEnhanceMsging');
         if (Options.enhanceMsging)
           checkbox.checked = true;
         checkbox.addEventListener ('change', function (){messageNav.setEnable(ById('togEnhanceMsging').checked)}, false);
        
      } catch (e) {
        t.cont.innerHTML = '<PRE>'+ e.name +' : '+ e.message +'</pre>';  
      }      
 
   },
   EmoClick: function(what) {
     document.getElementById ("mod_comm_input").value += " " + what + " ";
   },
   EmoHelp : function (){
   	var t = Tabs.Options;
       	unsafeWindow.BOEmoClick = t.EmoClick;
           var helpText = '<DIV style="max-height:430px; height:430px; overflow-y:auto">';
           helpText += '<TABLE width=98% cellspacing=0 cellpadding=2 border=0 bordercolor=black class=ptTab><tr>';
           var row=0;
           for (k in Smileys) {
            helpText += '<TR><TD><img class=emoicon src=\"'+Smileys[k]+'\" onclick="BOEmoClick(\''+k+'\')"></td><TD><font size=1>'+k+'</td></tr>';
           }
           helpText += '</table></div>';
       
       var inputtext=ById('mod_comm_input');
       var pop = new CPopup ('EmoHelp', 0, 0, 115, 455, true);
       pop.getMainDiv().innerHTML = helpText;
       pop.getTopDiv().innerHTML = '<CENTER><B><i>Les Smileys</b></center>';
       pop.show (true);
       
        ById("EmoHelp_outer").style.top = (getOffset(inputtext).top+30) +'px';
       ById("EmoHelp_outer").style.left = (getOffset(inputtext).left+230) +'px';
  },
   e_wideChanged : function (){
       GlobalOptions.pbWideScreen = ById('boWideOpt').checked;
       GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));  
   },
   hide : function (){
   },
   loadUrl : function (url){
        var t = Tabs.Options;
        t.mss.load (1, url, true);
        ById('boLoadStat').innerHTML = 'Chargement';
   },
   e_swfLoaded : function (){
        var t = Tabs.Options;
        ById('boLoadingSwf').style.display = 'none';
        ById('boSoundOpts').style.display = 'inline';
        t.volSlider.setValue (Options.alertSound.volume/100);
        t.loadUrl (Options.alertSound.soundUrl);
        setTimeout (function (){t.mss.setVolume (1, Options.alertSound.volume);}, 500);
        if (Options.alertSound.alarmActive && Options.alertSound.expireTime>unixTime())   {
          t.soundTheAlert();
        }
    },
    e_volChanged : function (val){
      var t = Tabs.Options;
      ById('boVolOut').innerHTML = parseInt(val*100);
      Options.alertSound.volume = parseInt(val*100);
      t.mss.setVolume (1, Options.alertSound.volume);
    },
    togOpt : function (checkboxId, optionName, callOnChange){
      var t = Tabs.Options;
      var checkbox = ById(checkboxId);
      if (Options[optionName])
        checkbox.checked = true;
      checkbox.addEventListener ('change', eventHandler, false);
      function eventHandler (){
        Options[optionName] = this.checked;
        saveOptions();
        if (callOnChange)
          callOnChange (this.checked);
        
        if (optionName=="DeleteMsgs4" || optionName=="DeleteMsg" || optionName=="DeleteMsgs0" || optionName=="DeleteMsgs1" || optionName=="DeleteMsgs2" || optionName=="DeleteMsgs3") {
           DeleteReports.init();
        }
      }
    },
    changeOpt : function (valueId, optionName, callOnChange){
      var t = Tabs.Options;
      var e = ById(valueId);
      e.value = Options[optionName];
      e.addEventListener ('change', eventHandler, false);
      function eventHandler (){
        Options[optionName] = this.value;
        saveOptions();
        if (callOnChange)
          callOnChange (this.value);
      }
    },
    e_watchChanged : function (){
      GlobalOptions.pbWatchdog = ById('boWatchEnable').checked;
      GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));  
    },
    e_wideChanged : function (){
      GlobalOptions.pbWideScreen = ById('boWideOpt').checked;
      GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));  
    },
    e_alertOptChanged : function (){
      	Options.alertConfig.aChat = ById('pcalertEnable').checked;
      	Options.alertConfig.aPrefix=ById('pcalertPrefix').value;      
      	Options.alertConfig.scouting=ById('pcalertScout').checked;      
      	Options.alertConfig.wilds=ById('pcalertWild').checked;
      	Options.alertConfig.MonQG=ById('pcalertQG').checked;
 	Options.alertConfig.embassy=ById('pcalertEmbassy').checked;
 	Options.alertConfig.empennage=ById('pcalertEmpennage').checked;
 	Options.alertConfig.marechal=ById('pcalertMarechal').checked;
 	Options.alertConfig.defBoost=ById('pcalertdefBoost').checked;
  	Options.alertConfig.mytroops=ById('pcalertMytroops').checked;
  	Options.alertConfig.food=ById('pcalertFood').checked;
  	Options.alertConfig.defense=ById('pcalertDefense').checked;
  	Options.alertConfig.defence=ById('pbalertDefend').checked;
    	Options.alertConfig.hq=ById('pcalertHQ').options[ById('pcalertHQ').selectedIndex].value;
  	Options.alertConfig.sendEmail=ById('pcalertSendEmail').checked;
  	Options.alertConfig.emailAddress=ById('pcalertEmailAddress').value;
  	Options.alertConfig.token=ById('pcalertToken').value;
  	Options.alertConfig.sendasWhisper=ById('pcalertSendAsWhisper').checked;
  	Options.alertConfig.sendtoAlly=ById('pcalertSendToAlly').checked;
        Options.alertConfig.raid=ById('BOalertraid').checked;
        Options.alertConfig.appro=ById('BOalertappro').checked;
        Options.alertConfig.autofo=ById('BOalertautofo').checked;
        Options.alertConfig.autots=ById('BOalertautots').checked;
      var mt = parseInt(ById('pcalertTroops').value);
      if (mt<1 || mt>120000){
        ById('pcalertTroops').value = Options.alertConfig.minTroops;
        ById('pcalerterr').innerHTML = '<font color=#600000><B>INVALID</b></font>';
        setTimeout (function (){ById('pcalerterr').innerHTML =''}, 2000);
        return;
      } 
      Options.alertConfig.minTroops = mt;
            var mt = parseInt(ById('pcalertTroops2').value);
      if (mt<1 || mt>120000){
        ById('pcalertTroops2').value = Options.alertConfig.minTroops2;
        ById('pcalerterr').innerHTML = '<font color=#600000><B>INVALID</b></font>';
        setTimeout (function (){ById('pcalerterr').innerHTML =''}, 2000);
        return;
      } 
      Options.alertConfig.minTroops2 = mt;  
      saveOptions();   
  },
}
/****************************  Onglet Personnalis�  ******************************/
Tabs.perso = {
  tabOrder : 99,
  tabLabel : Options.NewTabName,
  tabDisabled : !Options.NewTab,
  myDiv : null,
  timer : null,
  
  init : function (div){
    var t = Tabs.perso;
    t.myDiv = div;
    t.myDiv.innerHTML = '<CENTER><iframe src="'+Options.NewTabURL+'" width="950" height="'+(Options.HauteurBoite-30)+'" id="BOFrame"></iframe><BR></center>'; 
  },
  
  hide : function (){ 
  },
  
  show : function (){  
    var t = Tabs.perso;
  },
}


/****** AmÃ©liorations de la messagerie ********/
var messageNav = {
   mmFunc : null,
   MapFunc :null,
   mmsFunc : null,   
   init : function (){
     t = messageNav;
     t.MapFunc = new CalterUwFunc ('modal_maptile', [[/}\s*$/, 'setTimeout(function() { BOMdal_hook(n); },0); }']]);
     t.mmFunc = new CalterUwFunc ('modal_messages', [[/}\s*$/, 'setTimeout(messageNav_hook,0); }']]);
     t.mmsFunc = new CalterUwFunc ('modal_messages_send', [[/{\s*var params/i, '{\nif (modal_messages_send_hook()) return;\nvar params']]);
     unsafeWindow.messageNav_hook = t.hook;
     unsafeWindow.BOMdal_hook = t.testons;
     unsafeWindow.modal_messages_send_hook = t.msgSendHook;
     t.mmFunc.setEnable (true);
     t.mmsFunc.setEnable (true);
     t.MapFunc.setEnable (true);
   },
  setEnable : function (tf){
  },
  isAvailable : function (){
    t = messageNav;
    return t.mmFunc.isAvailable();
  }, 
  testons :function(uid) {
    if (uid!=null) {
      var div = ById('modalContent1');
      //if (uid=="11653192" || uid=="14904449" || uid=="11657114"){div.innerHTML="<center><img src=http://www.educol.net/tete-de-mort-t16657.jpg></center>";return;}
      var scr = document.createElement('div');
      scr.className = "maptilewrap";
      scr.innerHTML ="Recherche si ce joueur est en ligne...";
      div.appendChild(scr);
      var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
      params.checkArr = uid;
      new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
      onSuccess: function (rslt) {
         var p = rslt.data;
	 if (p[uid] == true) {
	         m = '<span style="color:green"><b>En Ligne !</b></span>';
	       } else {
	          m = '<span style="color:red"><b>Pas en ligne</b></span>';
          }  
         scr.innerHTML= m;
         
    },onFailure: function (rslt) {},
    
    });
   }
  },
  hook : function (){
    if (!Options.enhanceMsging)
      return;
    var div = ById('modal_msg_view_actions');
    div = ById('modal_msg_write_to').parentNode;
    div.innerHTML = '<TABLE><TR><TD class=xtab><b>A :</b> <INPUT type=text id=modal_msg_write_to></td>\
    <TD class=xtab></td></tr>\
    <tr><td></td><td></td></tr></table>\
    <table><tr><TD colspan=2><SPAN id=pt2fwdbut></span></td></tr></table>';
    ById('pt2fwdbut').innerHTML="Cc : <INPUT type=text id=message_cc>"; 
  },
  eventForward : function (){
    ById('modal_msg_write_subj').value = "TR: " + ById('modal_msg_view_subj').innerHTML.toString().stripTags();
    ById('modal_msg_write_to').value = '';
    var from = ById('modal_msg_view_from').children[0].innerHTML;
    var body = ById('modal_msg_view_body').innerHTML.replace(/\n/g, '').replace(/<br>/gi, '\n').stripTags().replace (/back$/i, '');
    ById('modal_msg_write_txt').value = '[Message original de '+ from +']\n'+ body;
    unsafeWindow.modal_messages_compose();
  },
  msgSendHook : function (){
    if (!Options.enhanceMsging)
      return;
    var to = ById("modal_msg_write_to").value.trim();
      var chaine = ById("message_cc").value;
      var tableau = chaine.split(";")
      if (tableau.length==0) tableau[0]=chaine;
      for (var i = 0; i < tableau.length; i++) {
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.emailTo = tableau[i] ;
        params.subject = "CC: "+ById("modal_msg_write_subj").value;
        params.message = ById("modal_msg_write_txt").value;
        params.requestType	 = 'COMPOSED_MAIL';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
         method: "post",
         parameters: params,
         onSuccess: function (rslt) {
              if (rslt.ok) ById('message_cc').value = "";
         },         
       });
      }  
    if (to.toLowerCase() != '<officiers>' || getMyAlliance()[0]==0) {  
      return false;
    }  
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.toIds = getMyAlliance()[0];
    params.subject = ById("modal_msg_write_subj").value +'';
    params.message = ById("modal_msg_write_txt").value;
    params.type = 'alliance';
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/sendMessage.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (rslt) {
            if (rslt.ok) {
                unsafeWindow.Modal.showAlert(unsafeWindow.g_js_strings.modal_messages_send.msgsent);
                ById('modal_msg_write_to').value = "";
                ById('modal_msg_write_subj').value = "";
                ById('modal_msg_write_txt').value = ""
            } else {
                unsafeWindow.Modal.showAlert(unsafeWindow.g_js_strings.modal_messages_send.enterexistingname)
            }
        },
        onFailure: function () {
          unsafeWindow.Modal.showAlert(unsafeWindow.g_js_strings.modal_messages_send.oopscompose)
        },
    });
    return true;
  },
}


var AttackDialog = {
  init : function (){
    var t = AttackDialog;
    t.modal_attackFunc = new CalterUwFunc ('modal_attack', [[/}\s*$/, 'attackDialog_hook(); }']]);
    unsafeWindow.attackDialog_hook = t.modalAttackHook;
    t.modal_attackFunc.setEnable (true);
  },

  setEnable : function (){
  },

  isKnightSelectAvailable : function (){
    var t = AttackDialog;
    return t.modal_attackFunc.isAvailable();
  },
  isAttackCityPickerAvailable : function (){
    var t = AttackDialog;
    return t.modal_attackFunc.isAvailable();
  },
    
  modalAttackHook : function (){
    var t = AttackDialog;
    if (Options.fixKnightSelect || Options.attackCityPicker){
      for (var i=1; i<6; i++)
        ById('modal_attack_tab_'+ i).addEventListener('click', t.e_changeMarchType, false);
    }
    if (Options.attackCityPicker){
      setTimeout (t.initCityPicker, 0);
    }      
  },
  
  initCityPicker : function (){
    var t = AttackDialog;
    var div = ById('modal_attack_target_numflag'); // as of KofC version 96;
    var mySpan;
    if (div) {
      div.parentNode.innerHTML += ' &nbsp; <SPAN id=modal_attack_citybuts></span>';
    } else {
      var span = ById('modal_attack_target_coords');   // KofC version 116+;
      span.parentNode.parentNode.firstChild.innerHTML += ' &nbsp; <SPAN id=modal_attack_citybuts></span>';
    }
    new CdispCityPicker ('ptatp', ById('modal_attack_citybuts'), false, t.e_CityButton);
    var cityIdx = Cities.byID[unsafeWindow.currentcityid].idx;
    thisCityBut = ById('ptatp_'+ cityIdx);
    thisCityBut.style.opacity = '0.5';
    thisCityBut.disabled = true;
    if (ById('modal_attack_tab_4').className=='selected' || ById('modal_attack_tab_3').className=='selected')   // don't do for attack or scout
      ById('modal_attack_citybuts').style.display = 'none';
  },
  
  e_CityButton : function (city){
    ById('modal_attack_target_coords_x').value = city.x;
    ById('modal_attack_target_coords_y').value = city.y;
    unsafeWindow.modal_attack_update_time();
  },
      
  e_changeMarchType : function (evt){
    var t = AttackDialog;
    var marchType = parseInt(evt.target.id.substr(17));  
    if (Options.attackCityPicker){
      if (marchType==3 || marchType==4)
        ById('modal_attack_citybuts').style.display = 'none';
      else
        ById('modal_attack_citybuts').style.display = 'inline';
    }
    if (Options.fixKnightSelect){
      var knightVal = 0;
      var selector = ById('modal_attack_knight'); 
      if (selector.length>1 && (marchType==4 || marchType==2))   // if 'attack' or 'reinforce'
        knightVal = 1;
      selector.selectedIndex = knightVal;
    }
  },  
}

/********* AmÃ©liorations des rapports d'alliance et liste des membres *********/
var AllianceReports = {
  checkPeriod : 300,
  allianceNames : [],
  saveArfunc : unsafeWindow.allianceReports,
  init : function (){
    t = AllianceReports;
    t.enable (Options.enhanceARpts);
    t.marvFunc = new CalterUwFunc ('modal_alliance_report_view', [['getReportDisplay', 'getReportDisplay_hook2']]);
    t.memListFunc = new CalterUwFunc ('membersInfo', [['commonstr.might','commonstr.might + "</td><td class=colcities>" + g_js_strings.commonstr.cities + "</td><td class=colava>Avatar</td><td class=collast>" + g_js_strings.membersInfo.lastonline'],['memberInfo[key].prestige', 'memberInfo[key].prestige+ "</td>");memhtml.push("<td class=colcities>" + memberInfo[key].cities + "</td><td class=colava><img width=35 src=" + memberInfo[key].avatarurl + "></td>");memhtml.push("<td class=collast>" + memberInfo[key].lastLogin']]);
    unsafeWindow.getReportDisplay_hook2 = t.getReportDisplayHook;
    unsafeWindow.getmembersInfo_hook = t.getMembersInfoHook;
    t.marvFunc.setEnable (true);
    t.enable_viewmembers(Options.enhanceViewMembers);
  },
  getReportDisplayHook : function (a, b){
    var x = '';
    try {
      x = unsafeWindow.getReportDisplay(a,b);  
    } catch (e){
      x = 'Error formatting report: '+ e;
    }
    return x;
  },
  enable_viewmembers : function (tf){
    	    t = AllianceReports;
   	    t.memListFunc.setEnable (tf);  
  },
  enable : function (tf){
    t = AllianceReports;
    if (tf)
      unsafeWindow.allianceReports = t.myAllianceReports;
    else
      unsafeWindow.allianceReports = t.saveArfunc;
  },
  myAllianceReports : function (pageNum){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    if (pageNum)
      params.pageNo = pageNum;
    params.group = "a";
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        displayReports (rslt.arReports, rslt.arPlayerNames, rslt.arAllianceNames, rslt.arCityNames, rslt.totalPages);
      },
      onFailure: function (rslt) {
      },
    }, false);

    function displayReports (ar, playerNames, allianceNames, cityNames, totalPages){
      var msg = new Array();
      var myAllianceId = getMyAlliance()[0];
      msg.push ("<STYLE>.msgviewtable tbody .myCol div {margin-left:5px; overflow:hidden; white-space:nowrap; color:#000}\
            .msgviewtable tbody .myHostile div {font-weight:600; color:#600}\
            .msgviewtable tbody .myGray div {color:#666}\
            .msgviewtable tbody .myRein div {color:#050}\
            .msgviewtable tbody .myWarn div {font-weight:600; color:#442200}\
            </style>");
      msg.push("<div class='modal_msg_reports'>");
      var rptkeys = unsafeWindow.Object.keys(ar);
      if (matTypeof(ar) != 'array') {
        if (Options.allowAlterAR)
          msg.push("<div id='modal_alliance_reports_tablediv' class='modal_msg_list'><table width=675 cellpadding='0' cellspacing='0' class='msgviewtable reportviewtable alliancetable'>");
        else
          msg.push("<div id='modal_alliance_reports_tabledivNKA' class='modal_msg_list'><table width=675 cellpadding='0' cellspacing='0' class='msgviewtable reportviewtable alliancetable'>");
        msg.push("<thead><tr><td width=105>Date</td><td width=40>Type</td><td width=150>"+uW.g_js_strings.commonstr.attacker+"</td><td>"+uW.g_js_strings.commonstr.target+"</td><td>Voir</td><td colspan=2>Dist. ville</tr></thead><tbody>");
        for (var i = 0; i < rptkeys.length; i++) {
          var rpt = ar[rptkeys[i]];
          var colClass = '"myCol"';
          rpt.marchType = parseInt(rpt.marchType);
          rpt.side0AllianceId = parseInt(rpt.side0AllianceId);
          var targetDiplomacy = getDiplomacy (rpt.side0AllianceId);
          if (rpt.marchType == 2){
            colClass = '"myCol myRein"';
          } else if (rpt.side1AllianceId != myAllianceId){
            colClass = '"myCol myHostile"';
          } else {
            if (parseInt(rpt.side0TileType) < 50){          // if wild
              if (parseInt(rpt.side0PlayerId) == 0)
                colClass = '"myCol myGray"';
              else
                colClass = '"myCol myWarn"';
            } else if (parseInt(rpt.side0PlayerId) == 0) {   // barb
              colClass = '"myCol myGray"';
            } else {
              if (targetDiplomacy == 'amicale')
                colClass = '"myCol myWarn"';
            }
          }
          msg.push ('<tr valign=top');
          if (i%2 == 0)
            msg.push(" class=stripe");
          msg.push("><TD class="+ colClass +"><div>");
          msg.push(unsafeWindow.formatDateByUnixTime(rpt.reportUnixTime));
          msg.push ('<BR>Rpt #');
          msg.push (rpt.reportId); 
          msg.push("</div></td><TD class="+ colClass  +"><div>");
          if (rpt.marchType == 1)
            msg.push (unsafeWindow.g_js_strings.commonstr.transport);
          else if (rpt.marchType == 3)
            msg.push (unsafeWindow.g_js_strings.commonstr.scout);
          else if (rpt.marchType == 2)
            msg.push ('Renf');
          else
            msg.push (unsafeWindow.g_js_strings.commonstr.attack);
          msg.push ("</div></td><TD class="+ colClass +"><div>");
          if (parseInt(rpt.side1PlayerId) != 0)
            msg.push('<a onclick=getInfoForAnUser("'+parseInt(rpt.side1PlayerId)+'");>'+escape(playerNames["p" + rpt.side1PlayerId])+"</a>");
          else
          msg.push ('?Unknown?');
          msg.push ('&nbsp;<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a><bR>');
          if (rpt.side1AllianceId != myAllianceId){
            msg.push (allianceNames['a'+rpt.side1AllianceId]);
            msg.push (' (');
            msg.push (getDiplomacy(rpt.side1AllianceId));
            msg.push (')');
          } else {
            msg.push ('<BR>');
          }
          msg.push ('</div></td>');
          msg.push ("<TD class="+ colClass  +"><DIV>");
          var type = parseInt(rpt.side0TileType);
          if (type < 50){                              // pour la TS
            msg.push(unsafeWindow.g_mapObject.types[type].toString().capitalize());
            msg.push(" Lvl " + rpt.side0TileLevel)
            if (parseInt(rpt.side0PlayerId) != 0) {   // IF OWNED, show owner ...
              	msg.push (' [');
  		msg.push ('<a @onclick=getInfoForAnUser("'+parseInt(rpt.side0PlayerId)+'");>' + escape(playerNames["p" + rpt.side0PlayerId])+'</a>');
              	msg.push ('] ');
            }
          } else {
            if (parseInt(rpt.side0PlayerId) == 0) {   //  barb
              msg.push(unsafeWindow.g_js_strings.commonstr.barbariancamp);
              msg.push(" Lvl " + rpt.side0TileLevel)
            } else {        // city
              msg.push ('<a onclick=getInfoForAnUser("'+ rpt.side0PlayerId+'");>' + escape(playerNames["p" + rpt.side0PlayerId])+'</a>');
              msg.push (' - ');
              msg.push (cityNames['c'+ rpt.side0CityId]);
            }
          }   
          msg.push ('&nbsp;<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a>');
          if (rpt.side0AllianceId!=0 && rpt.side0AllianceId!=myAllianceId){
            msg.push ('<BR>');
            msg.push (allianceNames['a'+rpt.side0AllianceId]);
            msg.push (' (');
            msg.push (targetDiplomacy);
            msg.push (')');
          }
          if (Options.allowAlterAR)
            msg.push("</div></td><TD class="+ colClass  +"><div><a onclick=' modal_alliance_report_view(\"");   // ONCLICK ???
          else
            msg.push("</div></td><TD class="+ colClass  +"><div><a onclick=' $(\"modal_alliance_reports_tabledivNKA\").id=\"modal_alliance_reports_tablediv\"; modal_alliance_report_view(\"");   // ONCLICK ???
          msg.push(rpt.reportId);
          msg.push('",');
          if (parseInt(rpt.side1AllianceId) == parseInt(Seed.allianceDiplomacies.allianceId))
            msg.push(1);
          else
            msg.push(0);
          msg.push(",");
          msg.push(rpt.side0TileType);
          msg.push(",");
          msg.push(rpt.side0TileLevel);
          msg.push(",");
          msg.push(rpt.side0PlayerId);
          msg.push(',"');
          if (parseInt(rpt.side0PlayerId) != 0)
            msg.push(escape(playerNames["p" + rpt.side0PlayerId]));
          else
            msg.push(unsafeWindow.g_js_strings.commonstr.enemy);
          msg.push('","');
          if (parseInt(rpt.side0PlayerId) != 0)
            msg.push(escape(playerNames["g" + rpt.side0PlayerId]));
          else
            msg.push(0)
          msg.push('","');
          if (parseInt(rpt.side1PlayerId) > 0)
            msg.push(escape(playerNames["p" + rpt.side1PlayerId]));
          msg.push('","');
          if (parseInt(rpt.side1PlayerId) != 0)
            msg.push(escape(playerNames["g" + rpt.side1PlayerId]));
          msg.push('",');
          msg.push(rpt.marchType);
          msg.push(",");
          msg.push(rpt.side0XCoord);
          msg.push(",");
          msg.push(rpt.side0YCoord);
          msg.push(",");
          msg.push(rpt.reportUnixTime);
          msg.push(",");
          if (parseInt(rpt.reportStatus) == 2)
            msg.push(1);
          else
            msg.push(0);
          if (rpt.side1XCoord) {
            msg.push(",");
            msg.push(rpt.side1XCoord);
            msg.push(",");
            msg.push(rpt.side1YCoord)
          } else {
            msg.push(",,");
          }
          msg.push(");return false;'><img border=0 src='http://cdn1.iconfinder.com/data/icons/woothemesiconset/16/search_button.png'></a></div></td></tr>");
        }
        msg.push("</tbody></table></div>");
      }
      msg.push("</div><div id='modal_report_list_pagination'></div>");
      ById('allianceContent').innerHTML = msg.join("");
      if (pageNum) {
        unsafeWindow.ctrlPagination("modal_report_list_pagination", totalPages, "allianceReports", pageNum)
      } else {
        unsafeWindow.ctrlPagination("modal_report_list_pagination", totalPages, "allianceReports")
      }
    }
  },
} 

/************************ Food Alerts  *************************/
var FoodAlerts = {
  minuteTimer:null,
  init : function (){
   var f = FoodAlerts;
   clearTimeout(f.minuteTimer);
   if (Options.enableFoodWarnTchat) 
  	f.e_eachMinute();
  },
  minuteTimer : null,
  e_eachMinute : function (){   
    var f = FoodAlerts;
    var now = unixTime();
    row = [];
    if (Options.enableFoodWarnTchat)  {
      for(i=0; i < Cities.numCities; i++) {
        var rp = getResourceProduction (Cities.cities[i].id);
        var foodleft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0])/3600;
        var usage = rp[1] - parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
        row[i] = rp[1] - usage;
          var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-usage) * 3600;
          var msg = '';
          if (timeLeft<0){
           }
          else if (timeLeft<(Options.foodWarnHours*3600)) {
                msg += 'Ma ville ' + Cities.cities[i].name.substring(0,10) + ' # ' +
                       Cities.cities[i].x +','+ Cities.cities[i].y + ' # ';
                msg += 'a besoin de pommes. Restant  : '+addCommasWhole(foodleft).replace(',',' ').replace(',',' ').replace(',',' ').replace(',',' ')+' ('+timestrShort(timeLeft)+') Production : '+addCommas(usage).replace(',',' ').replace(',',' ').replace(',',' ').replace(',',' ')+'/h';
                sendChat ("/a " + msg);
          }
      }  
    f.minuteTimer = setTimeout (f.e_eachMinute, 1800000);
   }
  },  
}

/************************ Alertes de la tour  ************************/
var TowerAlerts = {
  viewImpendingFunc : null,
  generateIncomingFunc : null,
  fixTargetEnabled : false,
  towerMarches : {}, 
  init : function (){
    var t = TowerAlerts; 
     
    var s = GM_getValue ('towerMarches_'+getServerId());
    if (s != null) t.towerMarches = JSON2.parse(s);
  },
  postToChatOptions : {aChat:false},
  secondTimer : null,

  setPostToChatOptions : function (obj){
    var t = TowerAlerts;
    t.postToChatOptions = obj;
    clearTimeout(t.secondTimer);  
    if (obj.aChat) t.e_eachSecond();
  },
  addTowerMarch : function (m){
    var t = TowerAlerts;
    var now = unixTime();
    for (k in t.towerMarches){
      if (t.towerMarches[k].arrival < now) {
        delete t.towerMarches[k];
      }
    }
    t.towerMarches['m'+m.mid] = {added:now, arrival:parseIntNan(m.arrivalTime) };
    setTimeout (function (){GM_setValue ('towerMarches_' +getServerId(), JSON2.stringify(t.towerMarches));}, 0);
  }, 
  getTowerMarch : function (mid){ 
    var t = TowerAlerts;
    return t.towerMarches['m'+mid];
  },
  e_eachSecond : function (){ 
    var t = TowerAlerts;
    var now = unixTime();

    if (matTypeof(Seed.queue_atkinc) != 'array'){
      for (var k in Seed.queue_atkinc){
        var m = Seed.queue_atkinc[k]; 
        if (Options.alertSound.alarmActive && (now > Options.alertSound.expireTime)) {
      		Tabs.Options.stopSoundAlerts(); 
         	setTimeout(function() {
         	   if (ById('botowertab'))
         	     ById('botowertab').style.display="none";
         	},2000);
         }
      
        if ((m.marchType==3 || m.marchType==4) && parseIntNan(m.arrivalTime)>now && t.getTowerMarch(m.mid)==null){
          t.addTowerMarch (m);
          t.postToChat (m, false);
          if (Options.alertSound.enabled){
               setTimeout(function() {
		         	   if (ById('botowertab'))
		         	     ById('botowertab').style.display="block";
         	},2000);
	        Tabs.Options.soundTheAlert(m);
	        if (m.arrivalTime > Options.alertSound.expireTime)
	          Options.alertSound.expireTime = m.arrivalTime;
    	  }
          if (Options.alertConfig.raid){
	    t.StopCityRaids(m.toCityId);
	  }  
	   if (Options.alertConfig.autofo){
	     AttackOptions.Running = false;
             updatebotbutton('AutoFO - OFF', 'pbautofstab');
	     saveAttackOptions();
	  } 
	   if (Options.alertConfig.autots){
	  	     CrestOptions.Running = false;
	              updatebotbutton('AutoTS - OFF', 'pbautotstab');
	  	     saveCrestOptions();
	  } 
	  if (Options.alertConfig.appro){
	    Tabs.TranspAuto.reapproState.running = false;
	    updatebotbutton('Appro - OFF', 'boreapprotab');
     	       
	  } 
        }
      }
    }
    t.secondTimer = setTimeout (t.e_eachSecond, 3000);
  },
  StopCityRaids : function (cityId){
  	      	var t = TowerAlerts;
  	      	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  	      	params.pf = 0;
  	      	params.ctrl = 'BotManager';
  	      	params.action = 'stopAll';
  	      	params.settings = {};
  	    	params.settings.cityId = cityId;
  	      	new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
  	      		  		method: "post",
  	      		         parameters: params,
  	      				 loading: true,
  	      				 onSuccess: function(transport){
  	      					var rslt = eval("(" + transport.responseText + ")");
  	      				 },
  	      		 });   
  },
  postToChat: function(m, force){
   var t = TowerAlerts;
   var postOptions = t.postToChatOptions;
   var troopsnames = ['Rav', 'Mil', 'Ecl', 'Piq', 'Pal', 'Arc', 'Cav', 'Lou', 'Wagon', 'Bali', 'Bel', 'Cat'];
   var tot = [];
   for (i = 0; i < 13; i++) 
	tot[i] = 0;
  
   if (m.marchType == null) 
		return;		
		
	if (m.marchType == 3) {
		if (!postOptions.scouting && !force) return;
		atkType = 'ECLAIREUR';
	} else {
		if (m.marchType == 4) {
				atkType = 'ATTAQUE';
		} else {
				return;
		}
	}
	
	var target, atkType, who;
	var city = Cities.byID[m.toCityId];
	if (city.tileId == m.toTileId) {
			target = 'VILLE ' + city.name + ' # ' + city.x + ',' + city.y+' #';
				if (postOptions.marechal) {
						var now = unixTime();
						marshallCombatScore = 0;
						var s = Seed.knights['city'+m.toCityId];
						if (s) {
							s = s["knt" + Seed.leaders['city'+m.toCityId].combatKnightId];
							if (s){
								marshallCombatScore = s.combat;
								// Option du boost par gans de courage (retirer)
								//if (s.combatBoostExpireUnixtime > now)
								//	marshallCombatScore *= 1.25;
							}
				                 }
				           target += ' (Marechal ' + parseInt(marshallCombatScore) + ') ';      
	                }
	        }else {
			if (!postOptions.wilds && !force) 
				return;
			target = 'TS';
			for (k in Seed.wilderness['city' + m.toCityId]) {
				if (Seed.wilderness['city' + m.toCityId][k].tileId == m.toTileId) {
					target += ' ' + Seed.wilderness['city' + m.toCityId][k].xCoord + ',' + Seed.wilderness['city' + m.toCityId][k].yCoord+' ';
					break;
				}
			}
		}
		if (postOptions.defBoost) {
		 var c=unsafeWindow.unixtime();
		 var boost="";
		 if (parseInt(Seed.playerEffects.defExpire)>c)
		 {
		  var f=parseInt(Seed.playerEffects.defExpire)-c;
		  boost = "def 20%";
		 }
		 if (parseInt(Seed.playerEffects.def2Expire)>c) {
		  var f=parseInt(Seed.playerEffects.defExpire)-c;		  
		  boost = "def 50%";
		 }
		 target += boost;
		}
		var attackermight = '';
		var allianceId = '';
		if (Seed.players['u' + m.pid]) {
			who = Seed.players['u' + m.pid].n;
			attackermight = parseInt(Seed.players['u' + m.pid].m);
            	        allianceId = Seed.players['u' + m.pid].a;
		} else {
			if (m.players && m.players['u' + m.pid]) {
				who = m.players['u' + m.pid].n;
				attackermight = parseInt(m.players['u' + m.pid].m);
                	         allianceId = m.players['u' + m.pid].a;
			} else {
				who = 'Inconnu';
			}
		}
		if (m.fromXCoord) 
			who += ' sur ' + m.fromXCoord + ',' + m.fromYCoord;
		if (m.knt) {
		  if (m.knt['cbt']!=undefined && m.knt['cbt']!=null) who += ' chevalier ' + m.knt['cbt'];
		}
		var diplomacy = getDiplomacy(allianceId);
		var arrivingDatetime = new Date();
		arrivingDatetime.setTime(m.arrivalTime * 1000);
		var msg = '';
		var subject = '';
		
		msg = 'Type : ' + atkType + '. ';
		if (!postOptions.MonQG && parseIntNan(postOptions.hq)>0) {
		 var mavilleId=Cities.byID[postOptions.hq];
		 msg += ' QG: ' + mavilleId.x + ','+mavilleId.y+' ';
		 
		}
		if (postOptions.empennage) {
		 msg += 'Emp ' + parseInt(Seed.tech['tch13']) + '. ';
		}
		
		msg += 'Cible : ' + target + '. ';
		msg += uW.g_js_strings.commonstr.attacker + ' : ' + who + ' (' + addCommas(attackermight).replace(',',' ').replace(',',' ') + ', ' + diplomacy + ').';
		msg +=' ** ARRIVEE ** : ';
		var totTroops = 0;
		for (k in m.unts) {
			var uid = parseInt(k.substr(1));
			msg += m.unts[k] + ' ' + unsafeWindow.unitcost['unt' + uid][0] + ', ';
			totTroops += m.unts[k];
		}
		
		// le paramérage du GQ ets fait	
		if (parseIntNan(postOptions.hq)>0) {
		 if (parseInt(m.toCityId)==parseInt(postOptions.hq)) {
		  // si QG 
		  if ((totTroops < postOptions.minTroops)) return;
		 
		 }
		 if (parseInt(m.toCityId)!=parseInt(postOptions.hq)) {
		 // si ville secondaires !
		 if ((totTroops < postOptions.minTroops2)) return;
				 
		 }
		} else {
		 if ((totTroops < postOptions.minTroops) && !force) 
			return;
		}
		msg = msg.slice(0, -2);
		msg += ' (arrive dans ' + unsafeWindow.timestr(parseInt(m.arrivalTime - unixTime())) + ' a ' + arrivingDatetime.toLocaleTimeString() +').' ;
		var msgpart1='';
		if (parseInt(Seed.citystats["city" + m.toCityId].gate) == 0 && Options.alertConfig.defence==true)
	        {
		   msg += ' ** SANCTUAIRE ** ';
		}
		if (parseInt(Seed.citystats["city" + m.toCityId].gate) == 1 && Options.alertConfig.defence==true)
		{
		  msg += ' ** JE DEFENDS ** ';
        	}
		if (city.tileId == m.toTileId) {
			var emb = getCityBuilding(m.toCityId, 8);
			if (emb.count <= 0) {
			 msg += ' Aucune ambassade';
			 var msgpart1 = msg;
			 msg ='';
			}
			if (emb.count > 0) {
				var availSlots = emb.maxLevel;
				for (k in Seed.queue_atkinc) {
					if (Seed.queue_atkinc[k].marchType == 2 && Cities.byID[Seed.queue_atkinc[k].fromCityId] == null) {
						--availSlots;
					}
				}
				msg += ' Mon ambassade (' + availSlots + '/' + emb.maxLevel + ')';
				var msgpart1 = msg;
				msg ='';
				if (postOptions.embassy) {
					var rownum = 0;
					enc = {};
					numSlots = 0;
					if (matTypeof(Seed.queue_atkinc) != 'array') {
						for (k in Seed.queue_atkinc) {
							march = Seed.queue_atkinc[k];
							if (march.marchType == 2) {
								++numSlots;
								city = march.toCityId;
								from = march.fromPlayerId;
								if (!enc[city]) 
									enc[city] = {};
								if (!enc[city][from]) 
									enc[city][from] = [];
								s = [];
								s[0] = parseInt(march.knightCombat);
								for (i = 1; i < 13; i++) {
									if (Options.encRemaining) 
										s[i] = parseInt(march['unit' + i + 'Return']);
									else 
										s[i] = parseInt(march['unit' + i + 'Count']);
								}
								enc[city][from].push(s);
							}
						}
					}					
					dest = m.toCityId;
					var embassyOccupied = false;
					if (enc[dest]) {
						embassyOccupied = true;
						msg += ' ** EMBASSADE **: ';
						for (p in enc[dest]) {
							try {
								if (Seed.players['u' +p]) {
									player = Seed.players['u' + p].n;
								} else {
									if (m.players && m.players['u' + p]) {
										player = m.players['u' + p].n;
									} else {
										player = 'Unknown';
									}
								}
							} 
							catch (err) {
								player = '???';
							}
							for (j = 0; j < enc[dest][p].length; j++) {
								knight = '';
								if (enc[dest][p][j][0] > 0) 
									knight = ' (' + enc[dest][p][j][0] + ')';
								var slot = j + 1;
								msg += '[slot' + slot + ': ' + player + knight + '->';
								for (i = 1; i < 13; i++) {
									num = enc[dest][p][j][i];
									if (num > 0) 
										msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[i - 1] + ', ';
									tot[i] += num;
								}
								msg += ']';
							}//for (j=0; j<enc[dest][p].length; j++)
						}//for (p in enc[dest])
					}//if (enc[dest])
					
				}// if (postOptions.embassy)
			}//if (emb.count > 0)
		}
		var msgpart2 = msg;
		msg ='';
		if (postOptions.mytroops) {
		msg += ' ** TROUPES ** : ';
		cityID = 'city' + m.toCityId;		
		for (r = 1; r < 13; r++) {
			num = parseInt(Seed.units[cityID]['unt' + r]);
			tot[r] += num;
			if (num > 0) 
				msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[r - 1] + ', ';
		}
		msg += '.';
		}
		var msgpart3 = msg;
		msg ='';  
		if (embassyOccupied) {
			msg += ' ** TOTAL ** : ';
			for (r = 1; r < 13; r++) {
				num = parseInt(tot[r]);
				if (num > 0) 
					msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[r - 1] + ', ';
			}
			msg += '.';
		}
		var msgpart4 = msg;
		msg='';
		if (postOptions.food) {
			var rp = getResourceProduction (m.toCityId);
      		var usage = parseInt(Seed.resources["city" + m.toCityId]['rec1'][3]);
      		var foodIncome = rp[1] - usage;
			var food = parseInt(Seed.resources['city'+ m.toCityId]['rec'+1][0] / 3600);
			var timeLeft = parseInt(Seed.resources["city" + m.toCityId]['rec1'][0]) / 3600 / (0-foodIncome) * 3600;
			var timeLeftShort  = timestrShort(timeLeft);
			msg += ' ** NOURRITURE **:';
			msg += ' '+addCommas(food).replace(',',' ').replace(',',' ').replace(',',' ') + ' (' +addCommas(foodIncome).replace(',',' ').replace(',',' ').replace(',',' ')+') -> Temps Restant : '+timeLeftShort+'. ';
		}
		var msgpart5 =msg;
		msg ='';
		if (Options.alertConfig.defense) {
			msg += ' ** DEFENSE **:';
			var fortifications = [];
			var fortificationsVal = [];
		fortifications['53'] = 'Arbalete';
          	fortifications['55'] = 'Trebuchet';
          	fortifications['60'] = 'Piege';
          	fortifications['61'] = 'Chausse';
          	fortifications['62'] = 'Palissade';       	
          	for (id in fortifications) {
          			if (IsNumeric(id)) {
      					var fortiName = fortifications[id];
     					var fortiVal = parseInt(Seed.fortifications['city' + m.toCityId]['fort'+id]);
     					msg += fortiVal +' '+fortiName+', ';  
          			} 
   			}
   		}
		var msgpart6 = msg;
		var msgpart7 = '';
		var msgpart8 = ' '+ postOptions.aPrefix + ' ';;
		msg = msgpart1 + msgpart2 + msgpart3 + msgpart4 + msgpart5 + msgpart6 + msgpart7 + msgpart8;
		if (postOptions.sendasWhisper) 	sendChat("/" + Seed.player.name + ' ' + msg); 
		if (postOptions.sendtoAlly) sendChat("/a " + msg); 
		if (postOptions.sendEmail) {
			var subject = unsafeWindow.domainName + ' >> ' +target + ' est en train ' + atkType + ' par ' + who + ' dans '+ arrivingDatetime;
			var email = postOptions.emailAddress;
			var error = false;
			if (email=="") error = true;
			if (subject=="") error = true;
			if (msgpart1=="") error = true;
			if (!error) sendEmail(Seed.player.name, "", email, subject, msg.replace("#",""));			
	       }
		
	}, // postToChat
} //TowerAlerts

function sendEmail (username, token, email, subject, msg){  

	
 var query = "?user="+username+"&email="+email+"&subject="+subject+"&msg1="+msg;
 query=query.replace(/#/g,'%23');
 new MyAjaxRequest("http://ddflux.org/email.php" + query, {
	      method: "POST",
	      onSuccess: function (rslt) {},
	      onFailure: function () {},
    });
} 

function getResourceProduction (cityId){
  var ret = [0,0,0,0,0];
  var now = unixTime (); 
  var wilds = [0, 0, 0, 0, 0];
  var w = Seed.wilderness["city" + cityId];
  for (var k in w){
    var type = parseInt(w[k].tileType);
    if (type==10 || type==11)
      wilds[1] += parseInt(w[k].tileLevel);
    else 
      wilds[type/10] += parseInt(w[k].tileLevel);
  }  
  knight = 0;       
  var s = Seed.knights["city" + cityId];
  if (s) {
    s = s["knt" + Seed.leaders["city" + cityId].resourcefulnessKnightId];
    if (s){
      var knight = parseInt(s.resourcefulness);
      if (s.resourcefulnessBoostExpireUnixtime > now)
        knight *= 1.25;
    }
  }
  var workerFactor = 1;
  var c = parseInt(Seed.citystats["city" + cityId]["pop"][0]);  // Current
																// population
  var w = parseInt(Seed.citystats["city" + cityId]["pop"][3]);  // Labor force
  if (w > c)
    workerFactor = c / w;
  
  for (var i=1; i<5; i++){
    var usage = Seed.resources["city" + cityId]["rec" + i];
    var items = 0;
    if (parseInt(Seed.playerEffects["r" + i + "BstExp"]) > now) {
      items = 0.25;
    }
    var tech = Seed.tech["tch" + i];
    ret[i] = parseInt((usage[2] * (1 + tech/10 + knight/100 + items + 0.05 * wilds[i]) * workerFactor + 100));
  }
  return ret;  
}

function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

function parseIntNan (n){
  x = parseInt(n, 10);
  if (isNaN(x))
    return 0;
  return x;
}
function parseIntCommas (n){
  n = n.split(',');
  n = n.join('');
  x = parseInt(n, 10);
  if (isNaN(x))
    return 0;
  return x;
}
function parseIntZero (n){
  n = n.trim();
  if (n == '')
    return 0;
  return parseInt(n, 10);
}


var CalterUwFunc = function (funcName, findReplace) {
  var t = this;
  this.isEnabled = false;
  this.isAvailable = isAvailable;
  this.setEnable = setEnable;
  this.funcName = funcName;
  this.funcOld = unsafeWindow[funcName];  
  this.funcNew = null;
  try {
    var funcText = unsafeWindow[funcName].toString();
    var rt = funcText.replace ('function '+ funcName, 'function');
    for (var i=0; i<findReplace.length; i++){
      x = rt.replace(findReplace[i][0], findReplace[i][1]);
      if (x == rt)
        return false;
      rt = x;
    }
    this.funcNew = rt;
  } catch (err) {
  }
      
  function setEnable (tf){
    if (t.funcNew == null)
      return;
    if (t.isEnabled != tf){
      if (tf){
      	var scr=document.createElement('script');
      	scr.innerHTML = funcName +' = '+ t.funcNew;
      	document.body.appendChild(scr);
        setTimeout ( function (){document.body.removeChild(scr);}, 0);
      	t.isEnabled = true;
      } else {
        unsafeWindow[t.funcName] = t.funcOld;
        t.isEnabled = false;
      }
    }
  }
  function isAvailable (){
    if (t.funcNew == null)
      return false;
    return true;
  }
};


/*******************   KOC Map interface ****************/
Map = {
/***
 0: bog
10: grassland
11: lake
20: woods
30: hills
40: mountain
50: plain
51: city / barb
53: misted city
***/
  generateBlockList : function(left, top, width) {
    var width5 = parseInt(width / 5);
    var bl = [];

    for (x=0; x<width5; x++){
      xx = left + (x*5);
      if (xx > 745)
        xx -= 750;
      for (y=0; y<width5; y++){
        yy = top + (y*5);
        if (yy > 745)
          yy -= 750;
        bl.push ('bl_'+ xx +'_bt_'+ yy);
      }
    }
    return bl.join(",");
  },

  callback : null,
  request : function (left, top, width, cb) {
    left = parseInt(left / 5) * 5;
    top = parseInt(top / 5) * 5;
    width = parseInt((width+4) / 5) * 5;
    var blockString = this.generateBlockList(left, top, width);
    Map.callback = cb;
    if (unsafeWindow.SANDBOX)
      return RequestMAPTEST(left, top, width, callback);
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.blocks = blockString;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchMapTiles.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        Map.callback(left, top, width, rslt);
      },
      onFailure: function (rslt) {
        Map.callback(left, top, width, rslt);
      }
    });
  },
};


/******** Export to KOC Attack **********/  

var exportToKOCattackBO = {
  troops : {},  
  
  init : function (){
      var t = exportToKOCattackBO;
      var isKOCattack = !(ById('KOCAttackToggle') == null);
      if (!isKOCattack) return
      for (var b=1; b<11; b++){
        t.troops['b'+ b] = [];
        for (var trp=0; trp<12; trp++){
          t.troops['b'+ b][trp] = 0;
        }
      }
      var s = GM_getValue ('atkTroops_'+ getServerId(), null);
      if (s != '' && s!=null){
        var trp = JSON2.parse(s);
        for (var b=1; b<11; b++){
          if (trp['b'+ b] && trp['b'+ b].length == 12)
            t.troops['b'+ b] = trp['b'+ b];
        }
      }
      window.addEventListener('unload', t.onUnload, false);
  },
  
  onUnload : function (){
    var t = exportToKOCattackBO;
    GM_setValue ('atkTroops_'+ getServerId(),  JSON2.stringify(t.troops));
  },
  
  doExport : function (coordList, city){
    var t = exportToKOCattackBO;
    var popExp = null;
    var cList = coordList;
    var curLevel = 0;
    var city = city;
    var troopDef = [
      ['Ravil', 1],
      ['Wagon', 9],
      ['Archers', 6],
      ['Cavalerie', 7],
      ['Lourds', 8],
      ['Baliste', 10],
      ['Cata', 12],
    ];
    var divKOCAttackExport=ById('BOdivKOCAttackExport');
    divKOCAttackExport.style.display='block';
    divKOCAttackExport.style.border='1px solid #000';
     divKOCAttackExport.style.top='100px';
      divKOCAttackExport.style.left='50px';
     var m = '<DIV id=BOdragExport class=boStat><table width="100%" cellspacing="0" border=0><tr><td class=boStat>Exporter les barbares directement dans KOC Attack</td><td id="idp_ExportX" onmouseover="this.style.cursor=\'pointer\'" style="color: rgb(255, 255, 255); background: none repeat scroll 0% 0% rgb(85, 85, 85); padding-left: 5px; padding-right: 5px; cursor: pointer;" valign="middle" align="right">X</td></tr></table></div><BR><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabPadNW>\
      <TR style="font-weight:bold; background-color:white"><TD>Type cible</td><TD style="padding:1px" align=center>#<BR>cibles</td><TD width=17></td>';
    for (var i=0; i<troopDef.length; i++)
      m += '<TD>'+ troopDef[i][0] +'</td>';
    m += '</tr>';
    for (var b=1; b<11; b++){
      m += '<TR><TD>Barb niv '+ b +'</td><TD align=right>'+ coordList['lvl'+b].length  +'&nbsp; &nbsp;</td><TD></td>'; 
      for (var td=0; td<troopDef.length; td++)
        m += '<TD><INPUT id=ptET_'+ b +'_'+ troopDef[td][1] +' type=text size=4 value="'+ t.troops['b'+ b][troopDef[td][1]-1] +'"></td>';
      m += '<TD width=90%><SPAN class=boldRed id=ptETerr_'+ b +'></span></tr>';
    } 
    m += '</table>';
    var isKOCattack = !(ById('KOCAttackToggle') == null);
    if (isKOCattack){
      m += '<BR><CENTER>'+ strButton20('Ajouter les coordonn&eacute;es dans KOC Attack', 'id=pbSrcDoBA') +'</center>';
    } else {
      m += 'KOC Attack n\'est pas lanc&eacute, impossible d\'exporter';
    } 
    m += '<CENTER><DIV style="width:70%" id=pbSrcExpResult></DIV></center>'; 
    divKOCAttackExport.innerHTML =  m;
    new CWinDrag (ById('BOdragExport'), divKOCAttackExport, true);
     ById('idp_ExportX').addEventListener ('click', function() { 
      ById('BOdivKOCAttackExport').style.display="none";
      ById('BOdivKOCAttackExport').innerHTML =  "";
     }, false);
    for (var b=1; b<11; b++)
      for (var td=0; td<troopDef.length; td++)
        ById('ptET_'+ b +'_'+ troopDef[td][1]).addEventListener ('change', validate, false);
     if (isKOCattack)    
      document.getElementById ('pbSrcDoBA').addEventListener ('click', doBulkAdd, false);    
    if (city != null){
      for (var i=0; i<Cities.numCities; i++)
        if (city.id == Cities.cities[i].id)
          break;
      if (i < Cities.numCities){
        setTimeout (function(){unsafeWindow.citysel_click(ById('citysel_'+ (i+1)));}, 0);
      }
    }
    function validate (e){
      var x = e.target.id.substr(5).split('_');
      var b = x[0];
      var trp = x[1];
      ById('ptETerr_'+ b).innerHTML = '';
      var x = parseIntZero (e.target.value);
      if (isNaN(x) || x<0 || x>100000){
        e.target.style.backgroundColor = 'red';
        ById('ptETerr_'+ b).innerHTML = 'Entr&eacute;e invalide';
        return;
      } else {
        e.target.style.backgroundColor = '';
        e.target.value = x;
        t.troops['b'+ b][trp-1] = x;
      }
      var tot = 0;
      for (var td=0; td<troopDef.length; td++)
        tot += parseIntZero(ById('ptET_'+ b +'_'+ [troopDef[td][1]]).value);
      if (tot<1 && cList['lvl'+ b].length>0 )
        ById('ptETerr_'+ b).innerHTML = 'No troops defined';
      if (tot>200000)
        ById('ptETerr_'+ b).innerHTML = 'Trop de troupes';
    }
      
    function doBulkAdd (){
      for (var b=1; b<11; b++){
        if (ById('ptETerr_'+ b).innerHTML != '')
          return;
        var tot = 0;
        for (var td=0; td<troopDef.length; td++)
          tot += t.troops['b'+b][troopDef[td][1]-1];
        if (tot<1 && cList['lvl'+ b].length>0){
          ById('ptETerr_'+ b).innerHTML = 'No troops defined';
          return; 
        } else if (tot>200000) {
          ById('ptETerr_'+ b).innerHTML = 'Trop de troupes';
          return; 
        }
      }    
      ById('pbSrcExpResult').innerHTML = '';
      setTimeout(function() { doNextLevel (); }, 100);
    }
    
    function endBulkAdd (msg){
      unsafeWindow.Modal.hideModalAll(); 
      curLevel = 0;
      ById('pbSrcExpResult').innerHTML += msg;
    }
    
    function doNextLevel (){
      while ( curLevel<10 && cList['lvl'+ ++curLevel].length==0)
        ;
      if (curLevel>=10){
        unsafeWindow.Modal.hideModalAll(); 
	curLevel = 0;
        ById('pbSrcExpResult').innerHTML += "Fini !";
        return;
      }
      setTimeout(function() {
       unsafeWindow.Modal.hideModalAll(); 
       unsafeWindow.modal_attack(4,0,0);
       new CwaitForElement ('BulkAddAttackDiv', 5000, e_attackDialog );
      }, 250);
    }
        
    function e_attackDialog (tf){
      if (!tf){
        endBulkAdd ('<SPAN class=boldRed>ERREUR: impossible d\'ouvrir la page attaque</span>');
        return;  
      } 
      var div = searchDOM (ById('BulkAddAttackDiv'), 'node.tagName=="DIV" && node.style.display=="none"', 10);
      if (div==null){
        endBulkAdd ('<SPAN class=boldRed>ERREUR: Unexpected attack dialog format (1).</span>');
        return;  
      }
      var ta = searchDOM (div, 'node.tagName=="TEXTAREA"', 10);
      var but = searchDOM (div, 'node.tagName=="A"', 10);
      if (ta==null || but==null){
        endBulkAdd ('<SPAN class=boldRed>ERREUR: Unexpected attack dialog format (2).</span>');
        return;  
      }
      for (var trp=1; trp<13; trp++){
        var inp = ById('modal_attack_unit_ipt' +trp);
        inp.value = t.troops['b'+curLevel][trp-1];
        if (t.troops['b'+curLevel][trp-1] > 0)
          inp.style.backgroundColor = 'yellow';
        else
          inp.style.backgroundColor = 'white';
      }
      div.style.display = 'block';
      ById('KOCAttackBulkAddForce').checked = true;
      
        var m = '';
        var list = cList['lvl'+ (curLevel)];
        for (i=0; i<list.length; i++)
          m += list[i].x +','+ list[i].y +'\n';
        ta.value = m;
      clickWinBO(unsafeWindow, but, 'click');
      unsafeWindow.Modal.hideModal();
      setTimeout (doNextLevel, 500);
    }    
  },
}
 /******** /********************************* Auto Dark Forest ***********************************/
Tabs.autoFO = {
  tabLabel: 'AutoFO',
  tabOrder : 12,
  tabDisabled : false,
  myDiv : null,
  MapAjax : new CMapAjax(),
  popFirst : true,
  opt : {},
  nextattack : null,
  searchRunning : false,
  tilesSearched : 0,
  tilesFound : 0,
  curX : 0,
  curY : 0,
  lastX : 0,
  firstX : 0,
  firstY : 0,
  lastY : 0,
  rallypointlevel:0,
  knt:{},
  barbArray:{},
  lookup:1,
  city:0,
  deleting:false,
  
    
  init : function (div){
    var t = Tabs.autoFO;
    t.myDiv = div;
    AddSubTabLink('AutoFO', t.toggleBarbState, 'pbautofstab');
    
    var m = '<DIV id=pbTowrtDivF class=boStat>ATTAQUE AUTOMATIQUE SUR LES FORETS OBSCURES - <input type=button value="?" id=boaideautofo class=boAide></div><TABLE id=pbbarbingfunctions width=100% height=0% class=pbTab><TR align="center">';
	 if (AttackOptions.Running == false) {
	       m += '<TD><INPUT id=AttSearch type=submit value="Attaque = OFF"></td>';
	       updatebotbutton("AutoFO - OFF", 'pbautofstab');
	   } else {
	       m += '<TD><INPUT id=AttSearch type=submit value="Attaque = ON"></td>';
	       updatebotbutton("AutoFO - ON", 'pbautofstab');
	   }
	  m += '<TD><INPUT id=troopselect type=submit value="Selections des troupes"></td>';
	  m += '<TD><INPUT id=Options type=submit value="Options"></td>';
	  m += '</tr></table></div>';
	  
	  m += '<DIV id=pbTraderDivD class=boStat>STATISTIQUES DES FORETS OBSCURES</div>';
	
	  m += '<TABLE id=pbbarbstats width=100% height=0% class=pbTab><TR align="left"><TR>';
	  for(i=0;i<Seed.cities.length;i++){
	  		m += '<TD>' + Seed.cities[i][1] +'</td>';
	  }
	  m+='</tr><TR>';
	  for(i=0;i<Seed.cities.length;i++){
	  		m += '<TD><DIV><span id='+ 'pdtotalcity' + i +'></span></div></td>';
	  }
	  m+='</tr><TR>';
	  for(i=0;i<Seed.cities.length;i++){
	  		m += '<TD><DIV><span id='+ 'pddatacity' + i +'></span></div></td>';
	  }
	  m+='</tr><TR>'
	   for(i=0;i<Seed.cities.length;i++){
	  		m += '<TD><DIV><span id='+ 'pddataarray' + i +'></span></div></td>';
	 }
	 m+='</tr></table><TABLE id=pbbarbstats width=100% height=0% class=pbTab><TR align="center"><TR>';
	 for (i=0;i<=7;i++) {
	 	m+='<TD><DIV><span id='+ 'pberror' + i +'></span></div></td>';
     }
     m+='</tr></table>';
     m += '<DIV id=pbTraderDivD class=boStat>OPTIONS POUR LES FORETS OBSCURES</div>';
     m += '<TABLE width=100% height=0% class=ptTab><TR align="center">';
     for(i=0;i<Seed.cities.length;i++){
        m += '<TR><TD>' + Seed.cities[i][1] +'</td>';
        for (w=1;w<=10;w++){
           m += '<TD class=pblevelopt><INPUT id=pbcity'+i+'level'+w+' type=checkbox unchecked=true>Lvl:'+w+'</td>';
        }
     }
    
     t.myDiv.innerHTML = m;

     saveAttackOptions();
     t.checkBarbData();

     for(i=0;i<Seed.cities.length;i++){
		var element = 'pdtotalcity'+i;
		if (t.barbArray[i+1] == undefined) ById(element).innerHTML = 'Pas de donn&eacute;e';
		else ById(element).innerHTML =  'Forets:' + t.barbArray[i+1].length;
     }
    
    for(i=0;i<Seed.cities.length;i++){
		for (w=1;w<=10;w++){
			ById('pbcity'+i+'level'+w).checked = AttackOptions.Levels[i+1][w]; 
		}
    }
    
	ById('AttSearch').addEventListener('click', function(){t.toggleBarbState(this)} , false);
	
	ById('boaideautofo').addEventListener('click', function(){
	 window.open(sitesupport+"?page=aide_autofo");
	} , false);
	
	ById('Options').addEventListener('click', t.barbOptions , false);
	ById('troopselect').addEventListener('click', t.troopOptions , false);
    var element_class = document.getElementsByClassName('pblevelopt');
    for (k=0;k<element_class.length;k++){
    	element_class[k].addEventListener('click', t.saveLevelOptions , false);
    }
   },
  
  saveLevelOptions : function(){
		for(i=0;i<Seed.cities.length;i++){
			AttackOptions.Levels[i+1][0]=false;
			for (w=1;w<=10;w++){
				var ele = ById('pbcity'+i+'level'+w);
				AttackOptions.Levels[i+1][w]=ele.checked;
				if (ele.checked)					
					AttackOptions.Levels[i+1][0]=true;
			}		
		}
		saveAttackOptions();
   },
   
  troopOptions: function(){
  	 var t = Tabs.autoFO;
	 var troopDef = [
	 ['Ravi', 1],
      ['Militiens', 2],
      ['Eclaireurs', 3],
      ['Piquiers', 4],
	  ['Paladins', 5],
      ['Archers', 6],
      ['Cavaleries', 7],
      ['C.Lourdes', 8],
      ['Wagons', 9],
      ['Balistes', 10],
      ['Beliers', 11],
	  ['Catapultes', 12],
     ];
  	 if(t.troopselect == null)	
		t.troopselect = new CPopup ('pbtroopselect', 0, 0, 830, 445, true, function(){t.saveTroops();});
  	 t.troopselect.centerMe (mainPop.getMainDiv());  
  	 var z= '<DIV id=pbTraderDivD class=boStat>SELECTIONS DES TROUPES</div><TABLE width=100%><TR>';
	 z+='<TD></td>';
	 for(var i=0; i<troopDef.length; i++)
		z+='<TD>'+troopDef[i][0]+'</td>';
	 z+='<TD>MIN dist</td><TD>MAX dist</td>';
	 for(i=0;i<10;i++){
	 	z += '<TR><TD>Niv '+(i+1)+': </td>';
	 	for(var j=0; j<troopDef.length; j++){
	 		z += '<TD><INPUT id="level'+i+'troop'+j+'" type=text size=4 maxlength=6 value="'+AttackOptions.Troops[i+1][j+1]+'" /></td>';
	 	}
		z+='<TD align=left><INPUT id=Mindist'+i+' type=text size=3 maxlength=3 value="'+AttackOptions.MinDistance[i+1]+'"</td>';
	 	z+='<TD align=right><INPUT id=dist'+i+' type=text size=3 maxlength=3 value="'+AttackOptions.Distance[i+1]+'"</td>';
	 	z+='</tr>';		 		
	 }
	 z+='</table>';
	  t.troopselect.getMainDiv().innerHTML = z;
	  t.troopselect.show(true);
  },
  
  barbOptions: function(){
  	 var t = Tabs.autoFO;
  	 if(t.barboptions == null)	
		t.barboptions = new CPopup ('pbbarboptions', 0,0, 375,350, true);
  	 t.barboptions.centerMe (mainPop.getMainDiv());  
	 t.barboptions.getTopDiv().innerHTML = '<CENTER><b>Options des '+unsafeWindow.g_js_strings.commonstr.darkForest+' pour le serveur '+getServerId()+'</b></CENTER>';
  	var y = '<DIV style="max-height:400px; overflow-y:auto;"><DIV class=boStat>GERER LES FORETS</div><TABLE width=100%>';
	   y +='<TR><TD style="margin-top:5px; text-align:center;"><INPUT id=pbresetbarbs type=submit value="Supprimer"></td>';
	   y +='<TD style="margin-top:5px; text-align:center;"><INPUT id=pbpaintbarbs type=submit value="Voir"></td>';
	   y += '<TD><SELECT id=pbcity type=list></td></tr></table>';
	   y +='<TD style="margin-top:5px; text-align:center;"><DIV class=boStat> OPTIONS </div></td><TABLE>';
     y +='<TR><TD>Interval d&rsquo;attaque : <INPUT id=pbsendint type=text size=4 maxlength=4 value='+ AttackOptions.SendInterval +' \> secondes</td></tr>';
     y +='<TR><TD>Distance max de recherche : <INPUT id=pbmaxdist type=text size=4 maxlength=4 value='+ AttackOptions.MaxDistance +' \></td></tr>';
     y +='<TR><TD>Garder <INPUT id=rallyclip type=text size=1 maxlength=2 value="'+AttackOptions.RallyClip+'" \> point(s) de ralliement(s) libre(s)</td></tr>';
     y +='<TR><TD><INPUT id=pbreport type=checkbox '+(AttackOptions.UpdateEnabled?'CHECKED':'')+'\> Relancer les recherches toutes les <INPUT id=pbmsgint type=text size=3 maxlength=3 value='+AttackOptions.UpdateInterval+' \>minutes</td></tr>';
	 y +='<TR><TD> Passer la ville apr&eacute;s <INPUT id=barbstopsearch type=text size=4 value='+AttackOptions.stopsearch+' \> essaies.</td></tr>';
     y +='<TR><TD>Methode : '+htmlSelector({distance:'Proches en premiers', level:'Niveaux &eacute;lev&eacute;s en premiers', lowlevel:'Niveaux faibles en premiers'}, AttackOptions.Method, 'id=pbmethod')+'</td></tr>';
     y +='<TR><TD>Priorit&eacute; du chevalier : '+htmlSelector({0:'Point de combat faible', 1:'Point de combat haut'}, AttackOptions.knightselector, 'id=barbknight')+'</td></tr>';
     y+='<tr><td>Remise &agrave; z&eacute;ro des compteurs : <input type=button value=RAZ id=BO_FO_razCompteur></table></td></tr></table>';
	   t.barboptions.getMainDiv().innerHTML = y;
	   t.barboptions.show(true);
	
	ById('BO_FO_razCompteur').addEventListener('click', function(){
	 AttackOptions.BarbsFailedTraffic=0;
	 AttackOptions.BarbsFailedKnight=0;
	 AttackOptions.BarbsFailedVaria=0;
	 AttackOptions.BarbsFailedMarais=0;
	 AttackOptions.BarbsFailedRP=0;
	 AttackOptions.BarbsFailedBog=0;
	 AttackOptions.BarbsTried=0;
	 for (var city=0;city<Seed.cities.length;city++)
	  AttackOptions.BarbsDone[city]=0;
	 
	 saveAttackOptions();
	},false);
	ById('pbcity').options.length=0;
	for (i=0;i<Seed.cities.length;i++){
		var o = document.createElement("option");
		o.text = Seed.cities[i][1]
		o.value = i+1;
		ById("pbcity").options.add(o);
	}
	   
	ById('pbpaintbarbs').addEventListener('click', function(){
	   t.showBarbs(ById("pbcity").value,Seed.cities[ById("pbcity").value -1][1]);
        },false);
	ById('pbresetbarbs').addEventListener('click', t.deletebarbs,false);
	ById('pbmethod').addEventListener('change', function(){
		AttackOptions.Method=ById('pbmethod').value;
		saveAttackOptions();
		t.checkBarbData();
	},false);
	ById('barbknight').addEventListener('change', function(){
		AttackOptions.knightselector=ById('barbknight').value;
		saveAttackOptions();
	},false);
	ById('pbreport').addEventListener('change', function(){
		AttackOptions.UpdateEnabled=ById('pbreport').checked;
		saveAttackOptions();
	},false);
	ById('pbmsgint').addEventListener('change', function(){
	        if (parseInt(ById('pbmsgint').value)<30) ById('pbmsgint').value=30;
		AttackOptions.UpdateInterval=parseInt(ById('pbmsgint').value);
		saveAttackOptions();
	},false);
    ById('pbsendint').addEventListener('change', function(){
		if(parseInt(ById('pbsendint').value) <5) //Set minimum attack interval to 5 seconds
			ById('pbsendint').value = 5;
		AttackOptions.SendInterval=parseInt(ById('pbsendint').value);
		saveAttackOptions();
	},false);
    ById('pbmaxdist').addEventListener('change', function(){
		if(parseInt(ById('pbmaxdist').value) > 100)
			ById('pbmaxdist').value = 100;
		AttackOptions.MaxDistance=parseInt(ById('pbmaxdist').value);
		saveAttackOptions();
	},false);
    ById('rallyclip').addEventListener('change', function(){
		AttackOptions.RallyClip=parseInt(ById('rallyclip').value);
		saveAttackOptions();
	},false);
    ById('barbstopsearch').addEventListener('change', function(){
		ById('barbstopsearch').value = parseInt(ById('barbstopsearch').value)>0?ById('barbstopsearch').value:1
		AttackOptions.stopsearch=parseInt(ById('barbstopsearch').value);
		saveAttackOptions();
	},false);    
  },
  
    showBarbs: function (citynumber,cityname) {
		var t = Tabs.autoFO;
		var popTradeRoutes = null;
		t.popTradeRoutes = new CPopup('pbShowBarbs', 0, 0, 500, 500, true, function() {clearTimeout (1000);});
		var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';       
		t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
		t.popTradeRoutes.getTopDiv().innerHTML = '<TD><B>Forests Obscures de la ville : '+cityname+'</td>';
		t.popTradeRoutes.centerMe (mainPop.getMainDiv());  
		t.paintBarbs(citynumber,cityname);
		t._addTabHeader(citynumber,cityname);
		t.popTradeRoutes.show(true)	;
	 },
  	paintBarbs: function(i,cityname){
	        var t = Tabs.autoFO;
				for (k=(t.barbArray[i].length-1);k>=0;k--){t._addTab(i,cityname,k+1,t.barbArray[i][k]['x'], t.barbArray[i][k]['y'],t.barbArray[i][k]['dist'], t.barbArray[i][k]['level']);}
	    },
	  
  _addTab: function(citynumber,cityname,queueId,X,Y,dist,level){
	 var t = Tabs.autoFO;
	 var row = ById('pbBars').insertRow(0);
	 row.vAlign = 'top';
	 row.insertCell(0).innerHTML = queueId;
	 row.insertCell(1).innerHTML = '<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+X+','+Y+')</a>';
	 row.insertCell(2).innerHTML = '';
	 row.insertCell(3).innerHTML = dist;
	 row.insertCell(4).innerHTML = level;
	 row.insertCell(5).innerHTML = '<a class="button20" id="barbdel_' + queueId + '"><span>Supprimer</span></a>';
	 ById('barbdel_' + queueId).addEventListener('click', function(){
		t.deleteBarbElement(citynumber,queueId,cityname, true);
	 }, false);
  },
	 
  _addTabHeader: function(citynumber,cityname) {
	 var t = Tabs.autoFO;
	 var row = ById('pbBars').insertRow(0);
	 row.vAlign = 'top';
	 row.insertCell(0).innerHTML = "Ordre";
	 row.insertCell(1).innerHTML = "Coords";
	 row.insertCell(2).innerHTML = "";
	 row.insertCell(3).innerHTML = "Dist.";
	 row.insertCell(4).innerHTML = "Niveau";
	 row.insertCell(5).innerHTML = '<a class="button20" id="barbdelAll"><span>TOUT supprimer</span></a>';
	 ById('barbdelAll').addEventListener('click', function(){
		t.deleteBarbsCity(citynumber,cityname);
	 }, false);
  },   
	   
  deleteBarbElement: function(citynumber,queueId,cityname,showFlag){
      var t = Tabs.autoFO;
      var queueId = parseInt(queueId);
      var myarray = t.barbArray[citynumber];
      if (myarray) {
        myarray.splice((queueId-1), 1);
        GM_setValue('DF_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId(), JSON2.stringify(myarray));
        t.checkBarbData();
        if (showFlag) t.showBarbs(citynumber,cityname);
      }
  },	  
  deleteBarbsCity: function(citynumber,cityname){
      var t = Tabs.autoFO;
      var queueId = parseInt(queueId);
	  AttackOptions.Update[citynumber][1] = 0;
      GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId())
      t.checkBarbData();
      t.showBarbs(citynumber,cityname);
      reloadKOC();
  },  
  saveTroops: function(){
    for(i=0;i<10;i++){
  	 	for (w=0;w<12;w++){
  	 		AttackOptions.Troops[i+1][w+1] = parseIntNan(ById('level'+i+'troop'+w).value);
  	 	}
		if(parseIntNan(ById('dist'+i).value) > AttackOptions.MaxDistance)
			ById('dist'+i).value = AttackOptions.MaxDistance;
		AttackOptions.MinDistance[i+1] = parseIntNan(ById('Mindist'+i).value);
  	 	AttackOptions.Distance[i+1] = parseIntNan(ById('dist'+i).value);	 		
	 }
	 saveAttackOptions();
  },
  
   deletebarbs: function(){
	for (i=1;i<=Seed.cities.length;i++){
		AttackOptions.Update[i][1] = 0;
		GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId())
	}
	reloadKOC();
   },

  checkBarbData: function(){
  	var t = Tabs.autoFO;
	if(!AttackOptions.Running) return;
	  for (i=1;i<=Seed.cities.length;i++){
		if (!AttackOptions.Levels[i][0]) continue; //Skip city if not selected
		t.barbArray[i] = [];
	  	var myarray = JSON2.parse(GM_getValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(),"[]"));
		
		if ((myarray == undefined || myarray.length == 0) && t.searchRunning==false) {
	  		t.lookup=i;
			if(parseInt(AttackOptions.Update[t.lookup][1]) >= parseInt(AttackOptions.stopsearch)) continue; //Skip if search results are empty more than X times
			t.searchRunning = true;
	  		t.opt.startX = parseInt(Seed.cities[(i-1)][2]);
	  		t.opt.startY = parseInt(Seed.cities[(i-1)][3]);  
	  		t.clickedSearch();
			break;
	  	}
		if (myarray){
			if(AttackOptions.Method == 'distance') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
			if(AttackOptions.Method == 'level') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['level']+a['dist'];b = b['level']+b['dist'];return a == b ? 0 : (a > b ? -1 : 1);});
			if(AttackOptions.Method == 'lowlevel') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['level']+a['dist'];b = b['level']+b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
	  		GM_setValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(), JSON2.stringify(t.barbArray[i]));
	  	}
		AttackOptions.Update[i][1] = 0;
		saveAttackOptions();
	  }
	  t.nextattack = setTimeout(t.getnextCity, parseInt((Math.random()*3000)+2000));
  },
  
  toggleBarbState: function(obj){
	var t = Tabs.autoFO;
	obj = ById('AttSearch');
	if (parseInt(AttackOptions.UpdateInterval)<30) AttackOptions.UpdateInterval=30;
	if (AttackOptions.Running == true) {
		AttackOptions.Running = false;
		obj.value = "Attaque = OFF";
	      	updatebotbutton('AutoFO - OFF', 'pbautofstab');
		saveAttackOptions();
		clearTimeout(t.nextattack);
		t.nextattack = null;
	} else {
		AttackOptions.Running = true;
		obj.value = "Attaque = ON";
		updatebotbutton('AutoFO - ON', 'pbautofstab');
		saveAttackOptions();
		t.checkBarbData();
		t.nextattack = setTimeout(t.getnextCity, parseInt((Math.random()*3000)+2000));
	}
  },
  
  barbing : function(){
     var t = Tabs.autoFO;
     var city = t.city;
     citynumber = Seed.cities[city-1][0];
     cityID = 'city' + citynumber; 
     t.getAtkKnight(cityID);
       t.getRallypointLevel(cityID);
       if (t.rallypointlevel > 11 ) t.rallypointlevel = 11;
	   var slots=0;
	   if (Seed.queue_atkp[cityID] != undefined){
	       for(var k in Seed.queue_atkp[cityID])
		    slots++;
		   if(Seed.queue_atkp[cityID].toSource() == "[]")
			slots = 0;
		} else
			slots=0; 
       
     
       
	   var element1 = 'pddatacity'+(city-1);
       ById(element1).innerHTML = 'Env: ' + AttackOptions.BarbsDone[city]; 
       var element2 = 'pddataarray'+(city-1); 
       ById(element2).innerHTML =  'PR: (' + slots + '/' + t.rallypointlevel +')';
	   
	   if ((t.rallypointlevel-AttackOptions.RallyClip) <= slots) { 
	    actionLog("AutoFO","Pas assez de slots PR disponible");
	    return;
	   }
	   if (t.knt.toSource() == "[]") {
	    actionLog("AutoFO","Pas de chevalier disponible");
	    return; 
	   }
	   var kid = t.knt[0].ID;
	   
	   if(t.barbArray[city].length > 0)
		var barbinfo = t.barbArray[city].shift();
	   else if(parseInt(AttackOptions.Update[city][1])==0){
		t.checkBarbData();
		return;
	   } else 
		return;
	
       var check=0;
       var barblevel = parseInt(barbinfo.level);
	 if (AttackOptions.Levels[city][barbinfo.level])
			check=1;
		
	 
        var xcoord = barbinfo['x'];
        var ycoord = barbinfo['y'];
        if (barbinfo.dist < AttackOptions.MinDistance[barblevel] || barbinfo.dist > AttackOptions.Distance[barblevel]){
			check=0;
			GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
			return;
		}

         // check troop levels in city
         var trps = AttackOptions.Troops[barblevel];
         var num_troops = 0;
         for (var ii=1; ii<13; ii++) {
	        if (parseInt(trps[ii]) > Seed.units[cityID]['unt'+ii]) check = 0;
	        num_troops += trps[ii];
         }
         if (num_troops == 0) check = 0;
 
       if (check == 0){
		t.barbArray[city].push(barbinfo);
		GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
		actionLog("AutoFO","Pas assez de troupes sur le niveau "+parseInt(barblevel));
		return;
	   }
	   
	var element = 'pdtotalcity'+(city-1);
		if (t.barbArray[city] == undefined) ById(element).innerHTML = 'Pas de donn&eacute;e';
		else ById(element).innerHTML =  'Forests :' + t.barbArray[city].length;
	   
       var xcoord = barbinfo['x'];
       var ycoord = barbinfo['y'];
       
 
       t.doBarb(citynumber,city,xcoord,ycoord,barblevel,kid,trps);
       saveAttackOptions();
  },

  getnextCity: function(){
	var t = Tabs.autoFO;
	if(t.searchRunning || !AttackOptions.Running) return;
	t.nextattack = setTimeout(t.getnextCity, parseInt((Math.random()*2)+AttackOptions.SendInterval)*1000);
	
	var city = t.city+1;
	if (city>Seed.cities.length){
		city=1;
	}
	t.city = city;
	if(AttackOptions.UpdateEnabled){
		var now = unixTime();
		if(now > parseInt(AttackOptions.Update[city][0] + (AttackOptions.UpdateInterval*60))){
			AttackOptions.Update[city][1]=0;
			t.barbArray[city] = []; //Clears data if last update was more than X minutes
			GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
		}
	}
	
	if(AttackOptions.Levels[city][0])
		t.barbing();
  },
  
  getRallypointLevel: function(cityId){
    var t = Tabs.autoFO;
    for (var o in Seed.buildings[cityId]){
  	var buildingType = parseInt(Seed.buildings[cityId][o][0]);
  	var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
  	if (buildingType == 12) t.rallypointlevel=parseInt(buildingLevel);
     }
  }, 
  
  getAtkKnight : function(cityID){
     var t = Tabs.autoFO;
     t.knt = new Array();
     t.getRallypointLevel(cityID);
     for (k in Seed.knights[cityID]){
     		if (Seed.knights[cityID][k]["knightStatus"] == 1 && Seed.leaders[cityID]["resourcefulnessKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["politicsKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["combatKnightId"] != Seed.knights[cityID][k]["knightId"] && Seed.leaders[cityID]["intelligenceKnightId"] != Seed.knights[cityID][k]["knightId"]){
     			t.knt.push ({
     				Name:   Seed.knights[cityID][k]["knightName"],
     				Combat:	Seed.knights[cityID][k]["combat"],
     				ID:		Seed.knights[cityID][k]["knightId"],
     			});
     		}
     }
     t.knt = t.knt.sort(function sort(a,b) {
							a = parseInt(a['Combat']);
							b = parseInt(b['Combat']);
							if(parseInt(AttackOptions.knightselector) > 0)
								return a == b ? 0 : (a > b ? -1 : 1);
							else
								return a == b ? 0 : (a < b ? -1 : 1);
							});
  },   
  doBarb: function(cityID,counter,xcoord,ycoord,level,kid,trps){
  	var t = Tabs.autoFO;
  	t.MapAjax.request (xcoord, ycoord, 1, function(left, top, width, rslt) {
  	   map = rslt.data;	
	   for (k in map){
		   if (xcoord==map[k].xCoord && ycoord==map[k].yCoord) {
		    if (parseInt(level)!=parseInt(map[k].tileLevel) && map[k].tileType==54 || map[k].tileType!=54) {
		     	AttackOptions.BarbsTried++;
		       	if (map[k].tileType==0) {
		       	 AttackOptions.BarbsFailedMarais++;
		       	 actionLog("AutoFO","Marais detecte sur "+ xcoord + ","+ycoord+" ");
		       	}else {
		       	 AttackOptions.BarbsFailedVaria++;
		       	 actionLog("AutoFO","Niveau different detecte sur "+ xcoord + ","+ycoord+" " + parseInt(map[k].tileLevel) +" au lieu de "+parseInt(level));
		       	}
		       	ById('pberror0').innerHTML = 'Tentative :'+ AttackOptions.BarbsTried; 
		       	ById('pberror5').innerHTML = 'Autre :' + AttackOptions.BarbsFailedVaria;
		       	ById('pberror7').innerHTML = 'Marais :' + AttackOptions.BarbsFailedMarais;
		       	GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
			saveAttackOptions();
		       return;
		    }
		   
		  
		  }
            }
     var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
     params.cid=cityID;
  		params.type=4;
  	    params.kid=kid;
  		params.xcoord = xcoord;
  		params.ycoord = ycoord;
		for (ii=1; ii<13; ii++) {
			if(parseInt(trps[ii]) > 0)
				params['u'+ii]=trps[ii];
                }
  		
  		AttackOptions.BarbsTried++;
  		ById('pberror0').innerHTML = 'Tentative :'+ AttackOptions.BarbsTried; 
  		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
  		         method: "post",
  		         parameters: params,
  		         loading: true,
  		         onSuccess: function (transport) {
				   var rslt = eval("(" + transport.responseText + ")");
				   if (rslt.ok) {
					 var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
					 var ut = unsafeWindow.unixtime();
					 var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
					 var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
					 for(i = 0; i <= unitsarr.length; i++){
						if(params["u"+i]){
						unitsarr[i] = params["u"+i];
						}
					 }
					 var currentcityid = params.cid;
					 unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
					 unsafeWindow.update_seed(rslt.updateSeed)
					 if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
					 var slots=0;
					 for(var k in Seed.queue_atkp['city'+cityID])
					  slots++;
					 if(Seed.queue_atkp['city'+cityID].toSource() == "[]")
					  slots = 0;
					 AttackOptions.BarbsDone[counter]++;
					 var element1 = 'pddatacity'+(counter-1);
					 ById(element1).innerHTML = 'Env: ' + AttackOptions.BarbsDone[counter]; 
					 var element2 = 'pddataarray'+(counter-1); 
					 ById(element2).innerHTML =  'PR: (' + slots + '/' + t.rallypointlevel +')';
					 var now = new Date().getTime()/1000.0;
					 now = now.toFixed(0);
					 GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
					 saveAttackOptions();
				   } else {
					 if (rslt.error_code != 8 && rslt.error_code != 213 && rslt.error_code == 210) AttackOptions.BarbsFailedVaria++;
					 if (rslt.error_code == 213)AttackOptions.BarbsFailedKnight++;
					 if (rslt.error_code == 210) AttackOptions.BarbsFailedRP++;
					 if (rslt.error_code == 8) AttackOptions.BarbsFailedTraffic++;
					 if (rslt.error_code == 104) {
					   AttackOptions.BarbsFailedBog++;
					   GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
					   saveAttackOptions();
					 }
					 ById('pberror2').innerHTML = 'Erreur Traffic :' + AttackOptions.BarbsFailedTraffic; 
					 ById('pberror3').innerHTML = 'Erreur PR : '+ AttackOptions.BarbsFailedRP;
					 ById('pberror4').innerHTML = 'Erreur Chev :' + AttackOptions.BarbsFailedKnight;
					 ById('pberror5').innerHTML = 'Autre :' + AttackOptions.BarbsFailedVaria;
					 ById('pberror6').innerHTML = 'Bug :' + AttackOptions.BarbsFailedBog;
					 }
  		         },
  		         onFailure: function () {}
  		 });
  	 saveAttackOptions();
  	 
  	 
  	 
  	});
  },
  
  sendreport: function(){
	  var t = Tabs.autoFO;
	  var total = 0;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.emailTo = Seed.player['name'];
    params.subject = "Barb Overview";
    var message = 'Barbing Stats: (Sent/Total)' + '%0A';
    for (x=1;x<=Seed.cities.length;x++){	 
    	message+= Seed.cities[x-1][1] + ': (' + AttackOptions.BarbsDone[x] + '/' + t.barbArray[x].length +')' + '%0A';
    }
    message += '%0A'+ 'Excess traffic errors: ' + AttackOptions.BarbsFailedTraffic +'%0A';
    message += 'Rallypoint errors: ' + AttackOptions.BarbsFailedRP +'%0A';
    message += 'Knight errors: ' + AttackOptions.BarbsFailedKnight +'%0A';
    message += 'Other errors: ' + AttackOptions.BarbsFailedVaria +'%0A';
    message += 'Actual sent attacks: ' + (AttackOptions.BarbsTried - AttackOptions.BarbsFailedTraffic - AttackOptions.BarbsFailedRP - AttackOptions.BarbsFailedKnight -  AttackOptions.BarbsFailedVaria) +'%0A';
    message += '%0A'+'%0A' + 'Food Gain (for '+AttackOptions.MsgInterval+' hour of barbing)' +'%0A';
    for (q=1;q<=Seed.cities.length;q++){
    	var cityID = 'city' + Seed.cities[q-1][0];
    	var gain = parseInt(Seed.resources[cityID]['rec1'][0] / 3600) - AttackOptions.Foodstatus[q];
    	message+= Seed.cities[q-1][1] + ': Start: ' + addCommas(AttackOptions.Foodstatus[q]) + ' End :' + addCommas(parseInt(Seed.resources[cityID]['rec1'][0] / 3600)) + ' Gain: ';
    	message += addCommas(gain)  + '%0A';
		total += gain;
    }
	message += '%0A Total food gain : '+addCommas(total)+'%0A';
    params.message = message;
    params.requestType = "COMPOSED_MAIL";
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (message) {
            var rslt = eval("(" + message.responseText + ")");
            if (rslt.ok) {
            } else {
            }
        },
        onFailure: function () {
        },
    });  
  },
  
  clickedSearch : function (){
    var t = Tabs.autoFO;
    
    t.opt.maxDistance = parseInt(AttackOptions.MaxDistance); 
    t.opt.searchShape = 'circle'; 
    t.mapDat = [];
    t.firstX =  t.opt.startX - t.opt.maxDistance;
    t.lastX = t.opt.startX + t.opt.maxDistance;
    t.firstY =  t.opt.startY - t.opt.maxDistance;
    t.lastY = t.opt.startY + t.opt.maxDistance;
    t.tilesSearched = 0;
    t.tilesFound = 0;
    t.curX = t.firstX;
    t.curY = t.firstY;
    var xxx = t.MapAjax.normalize(t.curX);
    var yyy = t.MapAjax.normalize(t.curY);
    var element = 'pddatacity'+(t.lookup-1);
    ById(element).innerHTML = uW.g_js_strings.commonstr.loadingddd+' : '+ xxx +','+ yyy;
   
    t.timerMap=setTimeout (function(){t.MapAjax.request (xxx, yyy, 15, t.mapCallback)}, 1000);
  },
  timerMap:null,
  mapCallback : function (left, top, width, rslt){
    var t = Tabs.autoFO;
    if (!t.searchRunning)
      return;
    if (!rslt.ok){
      t.stopSearch ('ERREUR : '+ rslt.errorMsg);
      return;
    }
    if (!AttackOptions.Running) {
   
     for (i=1;i<=Seed.cities.length;i++){
    		AttackOptions.Update[i][1] = 0;
    		GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId())
     }
     var element = 'pddatacity'+(t.lookup-1);
     ById(element).innerHTML = 'ANNULER PAR L\'UTILISATEUR';
     t.searchRunning = false;
     saveAttackOptions();
     return;
    }
    map = rslt.data;
	
    for (k in map){
	  if (map[k].tileType==54 && AttackOptions.Levels[t.lookup][map[k].tileLevel]){
	     var dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
		 if(dist <= parseInt(AttackOptions.MaxDistance))
			t.mapDat.push ({time:0,x:map[k].xCoord,y:map[k].yCoord,dist:dist,level:map[k].tileLevel});
	  }
    }
    
    t.tilesSearched += (15*15);

    t.curX += 15;
    if (t.curX > t.lastX){
      t.curX = t.firstX;
      t.curY += 15;
      if (t.curY > t.lastY){
		t.stopSearch('TRouv&eacute; : ' + t.mapDat.length);
        return;
      }
    }
    var x = t.MapAjax.normalize(t.curX);
    var y = t.MapAjax.normalize(t.curY);
    var element = 'pddatacity'+(t.lookup-1);
    ById(element).innerHTML = uW.g_js_strings.commonstr.loadingddd+' : '+ x +','+ y;
    t.timerMap=setTimeout (function(){t.MapAjax.request (x, y, 15, t.mapCallback)}, 1000);
  },
  
  stopSearch : function (msg){
    var t = Tabs.autoFO;
	var element = 'pddatacity'+(t.lookup-1);
        ById(element).innerHTML = msg;
	GM_setValue('DF_' + Seed.player['name'] + '_city_' + t.lookup + '_' + getServerId(), JSON2.stringify(t.mapDat));
	AttackOptions.Update[t.lookup][0] = unixTime();
	AttackOptions.Update[t.lookup][1]++;
        t.searchRunning = false;
	saveAttackOptions();
	t.checkBarbData();
	return;
  },
  
  hide : function (){
  
  },

  show : function (){
  
  },

}; 

Tabs.Raid = {
  tabDisabled : false,
  tabLabel: 'RAID',
  tabOrder : 13,
  myDiv : null,
  rallypointlevel:null,
  knt:{},
  Troops:{},
  city:0,
  raidtimer:null,
  rslt:{},
  save:{},
  stopping:false,
  resuming:false,
  deleting:false,
  stopprogress:0,
  stopcount:0,
  activecount:0,
  count:0,
  timerLookup:null,
  timerPaint:null,
  timerReport:null,
  init : function (div){
    var t = Tabs.Raid;
    t.myDiv = div;
	t.raidtimer = setTimeout(t.checkRaids, 6000); // verification au bout de 6 secondes aprs chargement de la boite
	var m = '<DIV class=boStat>CONFIGURATION DU RAID</div><TABLE width=100% height=0% class=pbTab><TR align="center">\
	    <td colspan=2><INPUT id=pbraidtab type=submit value="Stop Raids" class="tab"><INPUT id=pbraidtabRes type=submit value="Resume Raids" class="tab" >\
	    <INPUT id=pbraidtabDel type=submit value="Delete Raids" class="tab"></td>\
	    <TR align="center">';
	    m += '<TD><INPUT id=pbRaidStart type=submit value="Auto Reset = '+ (Options.RaidRunning?'ON':'OFF') +'" ></td>';
	    m += '<TD><INPUT id=pbsendraidreport type=checkbox '+ (Options.foodreport?'CHECKED':'') +'\> envoyer un rapport sur le raid toute les ';
	    m += '<INPUT id=pbsendreportint value='+ Options.MsgInterval +' type=text size=3 \> heures </td>';
	    m += '</tr></table></div>';
	    m += '<DIV class=boStat>MARCHES DU RAIDS ACTIVES</div><TABLE width=100% height=0% class=pbTab><TR align="center">';
	    m += '<TD><DIV style="margin-bottom:10px;"><span id=ptRaidCity></span></div></td></tr>';
	    m+='<TR><TD><DIV style="margin-bottom:10px;"><span id=ptRaidTimer></span></div></td></tr></table>';
	    m += '<DIV id=PaintRaids></div>';
	    m += '<DIV class=boStat>RAIDS MEMORISES</div><TABLE width=100% height=0% class=pbTab><TR align="center">';
	    m += '<DIV id=SavedRaids></div>';
	t.myDiv.innerHTML = m;
	if (Options.foodreport) {
	 t.timerReport=setInterval(t.sendreport, 1*60*1000);
	 }
	
	t.from = new CdispCityPicker ('ptRaidpicker', ById('ptRaidCity'), true, t.clickCitySelect, 0);
	ById('pbRaidStart').addEventListener('click', t.toggleRaidState, false);
	ById('pbsendraidreport').addEventListener('change', function(){
		Options.foodreport = ById('pbsendraidreport').checked;
		if (Options.foodreport) {
		   clearInterval(t.timerReport);
		   t.timerReport=setInterval(t.sendreport, 1*60*1000);
		 } else {
		  clearInterval(t.timerReport);
		 }
		saveOptions();
	}, false);
	ById('pbsendreportint').addEventListener('change', function(){
		Options.MsgInterval = parseInt(ById('pbsendreportint').value);
		saveOptions();
	}, false);
	
	ById('pbraidtab').addEventListener('click', t.StopAllRaids, false);
	ById('pbraidtabRes').addEventListener('click', t.ResumeAllRaids, false);
	ById('pbraidtabDel').addEventListener('click', t.DeleteAllRaids, false);
	
	
	var serverID = getServerId();
	t.save = GM_getValue ('SavedRaids_'+serverID);
	if (t.save != undefined) t.save = JSON2.parse (t.save);
	
	
  },
	
  lookup : function (){
      	var t = Tabs.Raid;
      	t.activecount=0;
      	t.stopcount=0;
      	for (c=0; c< Seed.cities.length;c++) {
      			cityID = 'city' + Seed.cities[c][0];    
   				for (b in Seed.queue_atkp[cityID]){
   					destinationUnixTime = Seed.queue_atkp[cityID][b]['destinationUnixTime']; 
   					MarchStatus = Seed.queue_atkp[cityID][b]['marchStatus'];
   					MarchType = Seed.queue_atkp[cityID][b]['marchType'];
   					botMarchStatus = Seed.queue_atkp[cityID][b]['botMarchStatus'];
   					if (MarchType == 9 &&  MarchStatus == 3 || MarchStatus==10) t.stopcount++;
   					else if (MarchType == 9) t.activecount++;

   				}
   		}
   		
   		if (t.resuming == false && t.stopping == false && t.deleting == false && t.activecount != 0)
				if (ById('pbraidtab')) ById('pbraidtab').value = 'Stop Raids ('+ t.activecount + ')'
			   	else if (t.resuming == false && t.stopping == false && t.deleting == false)
					if (ById('pbraidtab')) ById('pbraidtab').value = 'Stop Raids ('+ t.activecount + ')'
		   		if (t.resuming == false && t.resuming == false && t.deleting == false && t.stopcount !=0)
					if (ById('pbraidtabRes')) ById('pbraidtabRes').value = 'Resume Raids ('+ t.stopcount + ')'
		   		else if (t.resuming == false && t.stopping == false && t.deleting == false)
					if (ById('pbraidtabRes')) ById('pbraidtabRes').value = 'Resume Raids ('+ t.stopcount + ')'
		   		if (t.resuming == false && t.stopping == false && t.deleting == false && t.stopcount !=0)
					if (ById('pbraidtabDel')) ById('pbraidtabDel').value = 'Delete Raids ('+ t.stopcount + ')'
		   		else if (t.resuming == false && t.stopping == false && t.deleting == false)
			if (ById('pbraidtabDel')) ById('pbraidtabDel').value = 'Delete Raids ('+ t.stopcount + ')'
  }, 
   	
  paint : function ()	{
  	var t = Tabs.Raid;
  	
  	var botMarchStat = {0:'Inactive',
  						1:'Raiding',
  						2:'Returning',
  						3:'Stopped',
  						4:'Resting',
  						5:'Unknown',
  						7:'Situation Changed',
  						8:'Returning',
  						9:'Aborting'};
  	var botStat = {0:'Undefined',
  						1:'Marching',
  						2:'Returning',
  						3:'Stopped',
  						4:'Insufficient Troops',
  						5:'Max Raids Exceeded',
  						7:'Timed out',
  						8:'Resting'};
  	var o = '';
  	if (t.rslt.settings != undefined) o+= '<FONT size=2px><B>Minuteur RAID : '+ timestr( 86400 - ( unixTime() - t.rslt.settings.lastUpdated )) +'</b></font>';
  	ById('ptRaidTimer').innerHTML = o;
  	
  	var z ='<TABLE class=pbTab><TR><TD width=60px align=center><A onclick="pbStopAll('+t.cityId+')">STOP</a></td><TD width=70px>Temps</td><TD width=85px>Coords</td><TD width=50px>Niveau</td><TD width=50px></td><TD width=50px>&nbsp;</td></TR>';
  	if (t.rslt['queue'] != ""){
  		for (y in t.rslt['queue']) {
  			if (t.rslt['queue'][y]['botMarches'] != undefined) {
  				for (k in Seed.queue_atkp['city' + t.cityId]){
  					if (Seed.queue_atkp['city' + t.cityId][k]['marchId'] == t.rslt['queue'][y]['botMarches']['marchId']) {
  						botMarchStatus = Seed.queue_atkp['city' + t.cityId][k]['botMarchStatus'];
  						MarchStatus = Seed.queue_atkp['city' + t.cityId][k]['marchStatus'];
  						restPeriod = (Seed.queue_atkp['city' + t.cityId][k]['restPeriod']/60); 
  						destinationUnixTime = Seed.queue_atkp['city' + t.cityId][k]['destinationUnixTime'];
  						returnUnixTime = Seed.queue_atkp['city' + t.cityId][k]['returnUnixTime']
  						now = unixTime();
  						z+='<TR>';
  						if (MarchStatus == 1) z+='<TD align=center><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/attacking.jpg></td>';
  						if (MarchStatus == 8 && (destinationUnixTime - now) <= 0 && botMarchStatus !=3 && returnUnixTime > now) z+='<TD align=center><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/returning.jpg></td>';
  						if (MarchStatus == 3) z+='<TD align=center><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/autoAttack/raid_stopped_desat.png></td>';
  						if (MarchStatus == 4 || (returnUnixTime < now  && botMarchStatus !=3)) z+='<TD align=center><img src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/autoAttack/raid_resting.png></td>';
  						
  						if (destinationUnixTime >= now) z+='<TD>'+ timestr(Seed.queue_atkp['city' + t.cityId][k]['destinationUnixTime'] - unixTime())+'</td>';
  						if (destinationUnixTime <= now) {
  							if ((destinationUnixTime - now) <= 0 && returnUnixTime > now) z+='<TD>'+ timestr(returnUnixTime - now)+'</td>';
  							if (returnUnixTime <= now) z+='<TD>'+ timestr(now - returnUnixTime)+'</td>';
  						}
  					}
  				}
  				z+="<TD><a href='javascript:void(0)' onclick='cm.utils.CoordinateLinkController.onClick(event)' class='coordinateLink'>("+ t.rslt['queue'][y]['botMarches']['toXCoord'] +","+ t.rslt['queue'][y]['botMarches']['toYCoord']+")</a></td>";
  				z+='<TD align=center>'+ t.rslt['queue'][y]['botMarches']['toTileLevel'] +'</td>';
  				if (botMarchStatus == 3) z+='<TD><A onclick="pbEditRaid('+ y +')">Editer</a></td>';
	  				else z+='<TD><FONT COLOR= "CCCCCC">Editer</font></td>';
  				if (botMarchStatus == 3) z+='<TD align=center><A onclick="pbDeleteRaid('+ t.rslt['queue'][y]['botMarches']['marchId']+')">Supprimer</a></td>';
  				else z+='<TD align=center><FONT COLOR= "CCCCCC">Supprimer</font></td>';
  				z +='<TD width=25px></td><TD>Tps Rest : '+ timestr(restPeriod) +'</td>';
  				z+='</tr>';
  			}
  		}
  	}
  	z+='</table>';
  	if (t.rslt['queue'] == "") z ='<TABLE class=pbTab><TR><TD>Aucun Raid sur cette ville</td></TR>';
  	ById('PaintRaids').innerHTML = z;
  	
  	var check = true;
  		if (t.save != ""){
  			var a ='<TABLE class=pbTab><TR><TD width=60px></td><TD width=70px></td><TD width=85px>Coords</td><TD width=50px>Niveau</td><TD width=50px></td><TD width=50px></td></tr>';
  			for (y in t.save){
  				if (t.save[y] != undefined && t.cityId == t.save[y]['cityId']){
  					a +='<TR><TD align=center><A onclick="pbDeleteSavedRaid('+ t.save[y]['marchId'] +')">X</a></td>';
  					a +="<TD></td><TD><FONT COLOR='#CC0000'><a href='javascript:void(0)' onclick='cm.utils.CoordinateLinkController.onClick(event)' class='coordinateLink'>("+t.save[y]['toXCoord']+","+t.save[y]['toYCoord']+")</a></font></td>";
  					a +='<TD align=center>'+t.save[y]['toTileLevel']+'</td>';
  					a +='<TD><A onclick="pbEditSavedRaid('+ y +')">Editer</a></td>';
  					a +='<TD align=center><A onclick="pbAddRaid('+ t.save[y]['marchId']+')">Ajouter</a></td></tr>';
  					check = false;
  				}	
  			}
  			m+='</table>';
  		}
  		
  	if (check) a ='<TABLE class=pbTab><TR><TD>Aucun RAID dans cette ville !</td></TR>';
  	
  	ById('SavedRaids').innerHTML = a;  	
  	
  	unsafeWindow.pbDeleteRaid = t.DeleteRaid;
  	unsafeWindow.pbEditRaid = t.EditRaid;
  	unsafeWindow.pbAddRaid = t.AddRaid;
  	unsafeWindow.pbDeleteSavedRaid = t.DeleteSavedRaid;
  	unsafeWindow.pbEditSavedRaid = t.EditSavedRaid;
  	unsafeWindow.pbStopAll = t.StopCityRaids;
  },
  
  DeleteSavedRaid : function (Id){
    	  var t = Tabs.Raid;
    	  for (yy=0;yy<t.save.length;yy++){
    	  	if (t.save[yy]['marchId'] == Id){
    	  		  t.save.splice (yy,1);
    	  	}	
    	  }
    	  var serverID = getServerId();
    	  setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
    	  t.paint();
    },
  
  EditSavedRaid : function (y){
      var t = Tabs.Raid;
	  var pop = new CPopup ('pbEditRaid', 0,0, 750,350, true);
	  if (t.popFirst){
	    pop.centerMe (mainPop.getMainDiv());  
	    t.popFirst = false;
	  }
	  pop.getTopDiv().innerHTML = '<CENTER><B>Edition du Raid</b></center>';
	  cityId =  t.save[y]['cityId'];
	  
		  var m = '<BR><TABLE id=pbRaidAdd height=0% class=pbTab><TR align="center">';
		  m+='<TR></tr><TR><TD width=25px>X= <INPUT id=toXCoord type=text size=3 maxlength=3 value='+t.save[y]['toXCoord']+'></td>';
		  m+='<TD width=10px></td><TD widht=25px>Y= <INPUT id=toYCoord type=text size=3 maxlength=3 value='+ t.save[y]['toYCoord'] +'></td>';
		  m+='<TD width=25px></td><TD>Round Trip: '+ timestr((t.save[y]['returnUnixTime'] - t.save[y]['destinationUnixTime'])*2)+ '</td></tr></table>';

		  m += '<BR><TABLE id=pbRaidAdd width=100% height=0% class=pbTab><TR align="center">';
		  m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_1_50.jpg?6545"></td>';
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt1']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt2']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt3']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt4']) +'</td></tr>'
		  m += '<TR><TD><INPUT id=Unit1 type=text size=6 maxlength=6 value="'+ t.save[y]['unit1Count']+'"></td>';
		  m += '<TD><INPUT id=Unit2 type=text size=6 maxlength=6 value="'+ t.save[y]['unit2Count']+'"></td>';
		  m += '<TD><INPUT id=Unit3 type=text size=6 maxlength=6 value="'+ t.save[y]['unit3Count']+'"></td>';
		  m += '<TD><INPUT id=Unit4 type=text size=6 maxlength=6 value="'+ t.save[y]['unit4Count']+'"></td></tr>';
		  
		  m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_50.jpg?6545"></td>';
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt5']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt6']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_7_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt7']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_8_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt8']) +'</td></tr>'
		  m += '<TR><TD><INPUT id=Unit5 type=text size=6 maxlength=6 value="'+ t.save[y]['unit5Count']+'"></td>';
		  m += '<TD><INPUT id=Unit6 type=text size=6 maxlength=6 value="'+ t.save[y]['unit6Count']+'"></td>';
		  m += '<TD><INPUT id=Unit7 type=text size=6 maxlength=6 value="'+ t.save[y]['unit7Count']+'"></td>';
		  m += '<TD><INPUT id=Unit8 type=text size=6 maxlength=6 value="'+ t.save[y]['unit8Count']+'"></td></tr>';
		  
		  m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_50.jpg?6545"></td>';
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt9']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt10']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt11']) +'</td>'
		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_50.jpg?6545"></td>'
		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt12']) +'</td></tr>'
		  m += '<TR><TD><INPUT id=Unit9 type=text size=6 maxlength=6 value="'+ t.save[y]['unit9Count']+'"></td>';
		  m += '<TD><INPUT id=Unit10 type=text size=6 maxlength=6 value="'+ t.save[y]['unit10Count']+'"></td>';
		  m += '<TD><INPUT id=Unit11 type=text size=6 maxlength=6 value="'+ t.save[y]['unit11Count']+'"></td>';
		  m += '<TD><INPUT id=Unit12 type=text size=6 maxlength=6 value="'+ t.save[y]['unit12Count']+'"></td></tr></table>';
		  
		  m += '<BR><CENTER><SELECT id=AddKnights type=list></select></center>';
		  m+= '<BR><CENTER>'+ strButton20('Save', 'id=pbSaveRaid') +'</center>';
	        
	  pop.getMainDiv().innerHTML = m;
	  
	  t.getKnights(cityId);
	  
	  document.getElementById ('AddKnights').value =  t.save[y]['knightId'];
	  document.getElementById ('pbSaveRaid').addEventListener ('click', function(){
	  			t.save[y]['knightId'] = parseInt(document.getElementById ('AddKnights').value);
	  			t.save[y]['toXCoord'] = parseInt(document.getElementById ('toXCoord').value);
	  			t.save[y]['toYCoord'] = parseInt(document.getElementById ('toYCoord').value);
	  			t.save[y]['unit1Count'] = parseInt(document.getElementById ('Unit1').value);
	  			t.save[y]['unit2Count'] = parseInt(document.getElementById ('Unit2').value);
	  			t.save[y]['unit3Count'] = parseInt(document.getElementById ('Unit3').value);
	  			t.save[y]['unit4Count'] = parseInt(document.getElementById ('Unit4').value);
	  			t.save[y]['unit5Count'] = parseInt(document.getElementById ('Unit5').value);
	  			t.save[y]['unit6Count'] = parseInt(document.getElementById ('Unit6').value);
	  			t.save[y]['unit7Count'] = parseInt(document.getElementById ('Unit7').value);
	  			t.save[y]['unit8Count'] = parseInt(document.getElementById ('Unit8').value);
	  			t.save[y]['unit9Count'] = parseInt(document.getElementById ('Unit9').value);
	  			t.save[y]['unit10Count'] = parseInt(document.getElementById ('Unit10').value);
	  			t.save[y]['unit11Count'] = parseInt(document.getElementById ('Unit11').value);
	  			t.save[y]['unit12Count'] = parseInt(document.getElementById ('Unit12').value);
	  			var serverID = getServerId();
	  			setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
	  			pop.show (false);
	  }, false);
	  
	  pop.show (true);  	
    },
      
  EditRaid : function (y){
  	  var t = Tabs.Raid;
  	  var pop = new CPopup ('pbEditRaid', 0,0, 750,350, true);
  	  if (t.popFirst){
  	    pop.centerMe (mainPop.getMainDiv());  
  	    t.popFirst = false;
  	  }
  	  pop.getTopDiv().innerHTML = '<CENTER><B>Edit Raid</b></center>';
  	  cityId = t.rslt['queue'][y]['botMarches']['cityId'];
  	  
  		  var m = '<BR><TABLE id=pbRaidAdd height=0% class=pbTab><TR align="center">';
  		  m+='<TR></tr><TR><TD width=25px>X= <INPUT id=toXCoord type=text size=3 maxlength=3 value='+t.rslt['queue'][y]['botMarches']['toXCoord']+'></td>';
  		  m+='<TD width=10px></td><TD widht=25px>Y= <INPUT id=toYCoord type=text size=3 maxlength=3 value='+ t.rslt['queue'][y]['botMarches']['toYCoord'] +'></td>';
  		  m+='<TD width=25px></td><TD>Round Trip: '+ timestr((t.rslt['queue'][y]['botMarches']['returnUnixTime'] - t.rslt['queue'][y]['botMarches']['destinationUnixTime'])*2)+ '</td></tr></table>';

  		  m += '<BR><TABLE id=pbRaidAdd width=100% height=0% class=pbTab><TR align="center">';
  		  m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_1_50.jpg?6545"></td>';
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt1']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt2']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt3']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt4']) +'</td></tr>'
  		  m += '<TR><TD><INPUT id=Unit1 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit1Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit2 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit2Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit3 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit3Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit4 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit4Count']+'"></td></tr>';
  		  
  		  m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_50.jpg?6545"></td>';
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt5']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt6']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_7_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt7']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_8_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt8']) +'</td></tr>'
  		  m += '<TR><TD><INPUT id=Unit5 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit5Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit6 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit6Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit7 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit7Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit8 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit8Count']+'"></td></tr>';
  		  
  		  m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_50.jpg?6545"></td>';
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt9']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt10']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt11']) +'</td>'
  		  m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_50.jpg?6545"></td>'
  		  m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt12']) +'</td></tr>'
  		  m += '<TR><TD><INPUT id=Unit9 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit9Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit10 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit10Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit11 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit11Count']+'"></td>';
  		  m += '<TD><INPUT id=Unit12 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit12Count']+'"></td></tr></table>';
  		  
  		  m += '<BR><CENTER><SELECT id=AddKnights type=list></select></center>';
  		  m+= '<BR><CENTER>'+ strButton20('Save', 'id=pbRaidSave') +'</center>';
  	        
  	  pop.getMainDiv().innerHTML = m;
  	  
  	  t.getKnights(cityId);
  	  
  	  document.getElementById ('AddKnights').value =  t.rslt['queue'][y]['botMarches']['knightId'];
  	  document.getElementById ('pbRaidSave').addEventListener ('click', function(){
  	  	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  	  			  		
  	  	params.pf = 0;
  	      params.ctrl = 'BotManager';
  	  	params.action = 'editMarch';
  	  	params.settings = {};
  	  	params.settings.cityId = t.rslt['queue'][y]['botMarches']['fromCityId'];
  	  	params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};    	
  	  	params.queue[0].cityMarches.knightId = parseInt(document.getElementById ('AddKnights').value);
  	  	params.queue[0].cityMarches.toXCoord =  parseInt(document.getElementById ('toXCoord').value);
  	  	params.queue[0].cityMarches.toYCoord =  parseInt(document.getElementById ('toYCoord').value);
  	  	params.queue[0].cityMarches.unit0Count = 0; //document.getElementById ('Unit0').value;
  	  	params.queue[0].cityMarches.unit1Count =  parseInt(document.getElementById ('Unit1').value);
  	  	params.queue[0].cityMarches.unit2Count = parseInt(document.getElementById ('Unit2').value);
  	  	params.queue[0].cityMarches.unit3Count = parseInt(document.getElementById ('Unit3').value);
  	  	params.queue[0].cityMarches.unit4Count = parseInt(document.getElementById ('Unit4').value);
  	  	params.queue[0].cityMarches.unit5Count = parseInt(document.getElementById ('Unit5').value);
  	  	params.queue[0].cityMarches.unit6Count = parseInt(document.getElementById ('Unit6').value);
  	  	params.queue[0].cityMarches.unit7Count = parseInt(document.getElementById ('Unit7').value);
  	  	params.queue[0].cityMarches.unit8Count = parseInt(document.getElementById ('Unit8').value);
  	  	params.queue[0].cityMarches.unit9Count = parseInt(document.getElementById ('Unit9').value);
  	  	params.queue[0].cityMarches.unit10Count = parseInt(document.getElementById ('Unit10').value);
  	  	params.queue[0].cityMarches.unit11Count = parseInt(document.getElementById ('Unit11').value);
  	  	params.queue[0].cityMarches.unit12Count = parseInt(document.getElementById ('Unit12').value);
  	  	params.queue[0].cityMarches.marchId =  t.rslt['queue'][y]['botMarches']['marchId'];
  	  	
  	  	 new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
  				  		method: "post",
  				         parameters: params,
  						 loading: true,
  						 onSuccess: function(transport){
  							var rslt = eval("(" + transport.responseText + ")");
  		                      if (rslt.ok) {
  		                      		pop.show (false);
  									unsafeWindow.cityinfo_army();
  		                          setTimeout(unsafeWindow.update_seed_ajax, 250);
  		                          setTimeout(t.GetRaids, (750),Seed.cities[i][0]);
  								}
  						 },
  				 });
  	  	}, false);
  	  
  	  pop.show (true);  	
  },
  
  DeleteRaid : function (Id){
  	var t = Tabs.Raid;
  	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  	
  	for (y in t.rslt['queue']) {
  		if (t.rslt['queue'][y]['botMarches'] != undefined) {
	  		if (t.rslt['queue'][y]['botMarches']['marchId'] == Id) {
	  				marchId = t.rslt['queue'][y]['botMarches']['marchId'];
	  				cityId = t.rslt['queue'][y]['botMarches']['cityId'];
	  				knightId = t.rslt['queue'][y]['botMarches']['knightId'];
	  				toTileLevel = t.rslt['queue'][y]['botMarches']['toTileLevel'];
	  				returnUnixTime = t.rslt['queue'][y]['botMarches']['returnUnixTime'];
	  				destinationUnixTime = t.rslt['queue'][y]['botMarches']['destinationUnixTime'];
	  				toXCoord = t.rslt['queue'][y]['botMarches']['toXCoord'];
	  				toYCoord = t.rslt['queue'][y]['botMarches']['toYCoord'];
	  				var units = {};
	  				for (i=1;i<13;i++) units[i] = t.rslt['queue'][y]['botMarches']['unit'+i+'Count'];
	  		}
	  	}
  	}	
  	
  	params.pf = 0;
  	params.ctrl = 'BotManager';
  	params.action = 'deleteMarch';
  	params.marchId = marchId;
  	params.settings = {};
  	params.settings.cityId = cityId;
  	
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
  	         method: "post",
  	         parameters: params,
  			 loading: true,
  			 onSuccess: function(transport){
  				var rslt = eval("(" + transport.responseText + ")");
  	              if (rslt.ok) {
  	              	  var serverID = getServerId();
  	              	  t.save = GM_getValue ('SavedRaids_'+serverID);
  	              	  if (t.save == undefined) t.save =new Array();
					  else t.save = JSON2.parse (t.save);
					  
  	              	  t.save.push ({
  	              	  	marchId:		marchId,
  	              	  	cityId:   		cityId,
  	              	  	knightId:		knightId,
  	              	  	toTileLevel:	toTileLevel,
  	              	  	returnUnixTime:	destinationUnixTime,
  	              	  	returnUnixTime:	returnUnixTime,
  	              	  	toXCoord:		toXCoord,
  	              	  	toYCoord:		toYCoord,
  	              	  	unit1Count: 	units[1],
  	              	  	unit2Count: 	units[2],
  	              	  	unit3Count: 	units[3],
  	              	  	unit4Count: 	units[4],
  	              	  	unit5Count: 	units[5],
  	              	  	unit6Count: 	units[6],
  	              	  	unit7Count: 	units[7],
  	              	  	unit8Count: 	units[8],
  	              	  	unit9Count: 	units[9],
  	              	  	unit10Count: 	units[10],
  	              	  	unit11Count: 	units[11],
  	              	  	unit12Count: 	units[12],
  	              	  });
  	              	  var troops = Seed.units["city" + cityId];
                      for (var u = 1; u <= 12; ++u) {
                          var troop_number = parseInt(rslt["unit" + u + "Return"]);
                          if (isNaN(troop_number)) {
                              troop_number = parseInt(Seed.units["city" + cityId]["unt" + u]);
                          } else troop_number = parseInt(rslt["unit" + u + "Return"]) + parseInt(Seed.units["city" + cityId]["unt" + u]);
                          troops["unt" + u] = troop_number;
                      }
                      for (u in Seed.queue_atkp['city' + cityId]){
                      	if (Seed.queue_atkp['city' + cityId][u]['marchId'] == marchId){
							Seed.queue_atkp['city' + cityId][u] = "";
                      		unsafeWindow.seed.queue_atkp['city' + cityId] = Seed.queue_atkp['city' + cityId];
                      	}
                      }
                      
                      for (u in Seed.knights['city' + cityId]){
                      	if (Seed.knights['city' + cityId][u]['knightId'] == knightId){
                      		Seed.knights['city' + cityId][u]["knightStatus"] = 1;
                      		unsafeWindow.seed.knights['city' + cityId] = Seed.knights['city' + cityId];
                      	}
                      }
  	              	                              
  	              	  GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));
  	              	  t.save = null;
                      unsafeWindow.cityinfo_army();
  	                  setTimeout(unsafeWindow.update_seed_ajax, 250);
  	                  t.GetRaids(cityId);
  					}
  			 },
  	 });
},
  
  StopCityRaids : function (cityId){
    	var t = Tabs.Raid;
    	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

    	
    	params.pf = 0;
    	params.ctrl = 'BotManager';
    	params.action = 'stopAll';
    	params.settings = {};

  	    params.settings.cityId = cityId;
  	    		
    	 new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
    		  		method: "post",
    		         parameters: params,
    				 loading: true,
    				 onSuccess: function(transport){
    					var rslt = eval("(" + transport.responseText + ")");
    	                  if (rslt.ok) {
  								
    					  }
    				 },
    		 });   
    setTimeout(t.GetRaids, (750), cityId); 	
    },
  
  StopAllRaids : function (){
      	var t = Tabs.Raid;
      	if (t.stopping == true || t.resuming == true || t.deleting == true) return;
      	if (t.activecount == 0) return;
	    t.stopping = true; 	
	      	for (i=0;i<Seed.cities.length;i++){
		      	setTimeout(t.DoAllStop, (i*1500),i);
		     }
   },
   
   ResumeAllRaids : function (){
       	var t = Tabs.Raid;
       	if (t.stopping == true || t.resuming == true || t.deleting == true) return;
       	if (t.stopcount == 0) return;
       	t.resuming = true;
   			for (i=0;i<Seed.cities.length;i++){
   			    setTimeout(t.DoAllResume, (i*1500),i);
   			}
    },
   
   
   DeleteAllRaids : function (){
       	var t = Tabs.Raid;
       	if (t.stopping == true || t.resuming == true || t.deleting == true) return;
       	if (t.stopcount == 0) return;
       	t.deleting = true;
       	count=0;
       	t.count = t.stopcount;
	for (d=0; d< Seed.cities.length;d++) {
	   cityID = 'city' + Seed.cities[d][0];    
							for (e in Seed.queue_atkp[cityID]){
								destinationUnixTime = Seed.queue_atkp[cityID][e]['destinationUnixTime']; 
								MarchStatus = Seed.queue_atkp[cityID][e]['marchStatus'];
								MarchType = Seed.queue_atkp[cityID][e]['marchType'];
								if (MarchType == 9 && (botMarchStatus == 3 || MarchStatus == 3)) {
									count++;
									setTimeout(t.DoAllDelete, (count*1250), (Seed.queue_atkp[cityID][e]['marchId']),d,count);
								}
							}
				}
    }, 
    
  
  DoAllStop: function(i) {
    var t = Tabs.Raid;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  	params.pf = 0;
  	params.ctrl = 'BotManager';
  	params.action = 'stopAll';
  	params.settings = {};
  	params.settings.cityId = Seed.cities[i][0];
  	    		
  		 new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
  			  		method: "post",
  			         parameters: params,
  					 loading: true,
  					 onSuccess: function(transport){
  						var rslt = eval("(" + transport.responseText + ")");
  		                  if (rslt.ok) {
  		                  		t.stopprogress = t.stopprogress + (100/Seed.cities.length);
  		                  		
  		                  		if (ById("pbraidtab")) ById("pbraidtab").value='Stopping: '+ t.stopprogress.toFixed(0) + '%';
  		                  		if (t.stopprogress.toFixed(0) == 100) {
  		                  			 t.stopprogress = 0;
  		                  			 setTimeout(
  		                  			 function(){
  		                  			  if (ById("pbraidtab")) ById("pbraidtab").value='Stop Raids ('+ t.activecount + ')';
  		                  			  t.stopping = false;
  		                  			 
  		                  			 }, (5000));
  		                  			
  		                  		}		
  						  }
  						  else {
  						  		if (rslt.msg == "The system is busy, please try again later") setTimeout (t.DoAllStop, (2000),i);
  						  		else {
  					 	  			t.stopprogress = t.stopprogress + (100/Seed.cities.length);
  					 	  		        if (ById("pbraidtab")) ById("pbraidtab").value='Stopping: '+ t.stopprogress.toFixed(0) + '%';
  					 	  			
  					 	  			if (t.stopprogress.toFixed(0) == 100) {
  					 	  				 t.stopprogress = 0;
  					 	  				 setTimeout(function(){
  					 	  				 if (ById("pbraidtab")) ById("pbraidtab").value='Stop Raids ('+ t.activecount + ')';
  					 	  				 t.stopping = false;
  					 	  				 }, (5000));
  					 	  				 
  					 	  			}
  					 	  		}
  					 	  }
  					 },
    });  
  },

  DoAllResume: function(i) {
    var t = Tabs.Raid;
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  	params.pf = 0;
  	params.ctrl = 'BotManager';
  	params.action = 'resumeAll';
  	params.settings = {};
    params.settings.cityId = Seed.cities[i][0];
  	    		
  		 new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
  			  		method: "post",
  			         parameters: params,
  					 loading: true,
  					 onSuccess: function(transport){
  						var rslt = eval("(" + transport.responseText + ")");
  		                  if (rslt.ok) {
  		                  		t.stopprogress = t.stopprogress + (100/Seed.cities.length);
  		                  		if (ById("pbraidtabRes")) ById("pbraidtabRes").value='Resuming: '+ t.stopprogress.toFixed(0) + '%';			
  		                  		if (t.stopprogress.toFixed(0) == 100) {
  		                  			 t.stopprogress = 0;
  		                  			 setTimeout(function(){
  		                  			 
  		                  			 if (ById("pbraidtabRes")) ById("pbraidtabRes").value='Resume Raids ('+ t.stopcount + ')';
  					 	
  		                  			 t.resuming = false;
  		                  			 }, (5000));
  		                  		}		
  						  } else {
  						  		if (rslt.msg == "The system is busy, please try again later") setTimeout (t.DoAllResume, (2000),i);
  						  		else {
  					 	  			t.stopprogress = t.stopprogress + (100/Seed.cities.length);
  					 	  			if (ById("pbraidtabRes")) ById("pbraidtabRes").value='Resuming: '+ t.stopprogress.toFixed(0) + '%';
  					 	  			if (t.stopprogress.toFixed(0) == 100) {
  					 	  				 t.stopprogress = 0;
  					 	  				 setTimeout(function(){
  					 	  				 if (ById("pbraidtabRes")) ById("pbraidtabRes").value='Resume Raids ('+ t.stopcount + ')';
  					 	  				 t.resuming = false;}, (5000));
  					 	  			}	
  					 	  		}
  					 	  }
  					 },
    });  
  },
  
  DoAllDelete : function (Id,city,count){
    	var t = Tabs.Raid;
    	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    	cityID = 'city'+ Seed.cities[city][0];
    	for (f in Seed.queue_atkp[cityID]){
    		if (Seed.queue_atkp[cityID][f]['marchId'] == Id) {
    				marchId = Seed.queue_atkp[cityID][f]['marchId'];
    				cityId = Seed.queue_atkp[cityID][f]['cityId'];
    				knightId = Seed.queue_atkp[cityID][f]['knightId'];
    				toTileLevel = Seed.queue_atkp[cityID][f]['toTileLevel'];
    				returnUnixTime = Seed.queue_atkp[cityID][f]['returnUnixTime'];
    				destinationUnixTime = Seed.queue_atkp[cityID][f]['destinationUnixTime'];
    				toXCoord = Seed.queue_atkp[cityID][f]['toXCoord'];
    				toYCoord = Seed.queue_atkp[cityID][f]['toYCoord'];
    				var units = {};
    				for (i=1;i<13;i++) units[i] = Seed.queue_atkp[cityID][f]['unit'+i+'Count'];
    		}
    	}
    	
    	params.pf = 0;
    	params.ctrl = 'BotManager';
    	params.action = 'deleteMarch';
    	params.marchId = marchId;
    	params.settings = {};
    	params.settings.cityId = cityId;
    	
      new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
    	         method: "post",
    	         parameters: params,
    			 loading: true,
    			 onSuccess: function(transport){
    				var rslt = eval("(" + transport.responseText + ")");
    	              if (rslt != "") {
    	              	  var serverID = getServerId();
    	              	  t.save = GM_getValue ('SavedRaids_'+serverID, "[]");
    	              	  if (t.save != undefined) t.save = JSON2.parse (t.save);
    	              	  if (t.save == undefined) t.save =new Array();
  
    	              	  t.save.push ({
    	              	  	marchId:		marchId,
    	              	  	cityId:   		cityId,
    	              	  	knightId:		knightId,
    	              	  	toTileLevel:	toTileLevel,
    	              	  	returnUnixTime:	destinationUnixTime,
    	              	  	returnUnixTime:	returnUnixTime,
    	              	  	toXCoord:		toXCoord,
    	              	  	toYCoord:		toYCoord,
    	              	  	unit1Count: 	units[1],
    	              	  	unit2Count: 	units[2],
    	              	  	unit3Count: 	units[3],
    	              	  	unit4Count: 	units[4],
    	              	  	unit5Count: 	units[5],
    	              	  	unit6Count: 	units[6],
    	              	  	unit7Count: 	units[7],
    	              	  	unit8Count: 	units[8],
    	              	  	unit9Count: 	units[9],
    	              	  	unit10Count: 	units[10],
    	              	  	unit11Count: 	units[11],
    	              	  	unit12Count: 	units[12],
    	              	  });
    	              	  
    	              	  var troops = Seed.units["city" + cityId];
    	              	  for (var u = 1; u <= 12; ++u) {
    	              	      var troop_number = parseInt(rslt["unit" + u + "Return"]);
    	              	      if (isNaN(troop_number)) {
    	              	          troop_number = parseInt(Seed.units["city" + cityId]["unt" + u]);
    	              	      } else troop_number = parseInt(rslt["unit" + u + "Return"]) + parseInt(Seed.units["city" + cityId]["unt" + u]);
    	              	      troops["unt" + u] = troop_number;
    	              	  }
    	              	  
    	              	  setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
                          unsafeWindow.cityinfo_army();	  
    	                  setTimeout(unsafeWindow.update_seed_ajax, 250);
    					}
    			 },
    	 });
  		  	 t.stopprogress = count * (100/t.count);
 		  	 if (ById("pbraidtabRes")) ById("pbraidtabDel").value='Deleting: '+ t.stopprogress.toFixed(0) + '%';	 	
  		  	 if (t.stopprogress.toFixed(0) == 100) {
  		  	 	 t.stopprogress = 0;
  		  	 	 t.GetRaids(cityId);
  	}	
    	 
},
AddRaid : function (Id){
    	var t = Tabs.Raid;
    	var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    	update = {};
    	
    	params.pf = 0;
    	params.ctrl = 'BotManager';
    	params.action = 'saveMarch';
    	params.settings = {};
    	params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};
    	
    	for (y in t.save){
    		if (t.save[y]['marchId'] == Id){
	    		params.settings.cityId = t.save[y]['cityId'];
	    		params.queue[0].cityMarches.knightId = t.save[y]['knightId']; 
	    		params.queue[0].cityMarches.toXCoord = t.save[y]['toXCoord'];
	    		params.queue[0].cityMarches.toYCoord = t.save[y]['toYCoord'];
	    		params.queue[0].cityMarches.unit0Count = 0;
	    		params.queue[0].cityMarches.unit1Count = t.save[y]['unit1Count'];
	    		params.queue[0].cityMarches.unit2Count = t.save[y]['unit2Count'];
	    		params.queue[0].cityMarches.unit3Count = t.save[y]['unit3Count'];
	    		params.queue[0].cityMarches.unit4Count = t.save[y]['unit4Count'];
	    		params.queue[0].cityMarches.unit5Count = t.save[y]['unit5Count'];
	    		params.queue[0].cityMarches.unit6Count = t.save[y]['unit6Count'];
	    		params.queue[0].cityMarches.unit7Count = t.save[y]['unit7Count'];
	    		params.queue[0].cityMarches.unit8Count = t.save[y]['unit8Count'];
	    		params.queue[0].cityMarches.unit9Count = t.save[y]['unit9Count'];
	    		params.queue[0].cityMarches.unit10Count = t.save[y]['unit10Count'];
	    		params.queue[0].cityMarches.unit11Count = t.save[y]['unit12Count'];
	    		params.queue[0].cityMarches.unit12Count = t.save[y]['unit12Count'];
    		}
    	}	
    	 
    	 new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
    		  		method: "post",
    		         parameters: params,
    				 loading: true,
    				 onSuccess: function(transport){
    					var rslt = eval("(" + transport.responseText + ")");
    	                  if (rslt.ok) {
								t.GetRaids(params.settings.cityId);
      					        unsafeWindow.cityinfo_army();
      	                  		setTimeout(unsafeWindow.update_seed_ajax, 250);
      	                  		for (yy=0;yy<t.save.length;yy++){
      	                  			if (t.save[yy]['marchId'] == Id){
      	                  				  t.save.splice (yy,1);
      	                  			}	
      	                  		}
      	                  		var serverID = getServerId();
      	                  		setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
      	                  		t.paint();
    					 } else {
  				 		  	  alert('Error: '+ rslt.msg);  	
    					 }
    				 },
    		 });    	
    },
    
        
  getKnights : function(cityId){
         var t = Tabs.Raid;
         var knt = new Array();
         var status ="";
         for (k in Seed.knights['city' + cityId]){
         		if ( Seed.leaders['city' + cityId]["resourcefulnessKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["politicsKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["combatKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["intelligenceKnightId"] != Seed.knights['city' + cityId][k]["knightId"]){
         		   if (Seed.knights['city' + cityId][k]["knightStatus"] == 1 ) status = "Free";
         		   else status = "Marching";
         			knt.push ({
         				Name:   Seed.knights['city' + cityId][k]["knightName"],
         				Combat:	parseInt(Seed.knights['city' + cityId][k]["combat"]),
         				ID:		Seed.knights['city' + cityId][k]["knightId"],
         				Status: status,
         			});
         		}
         }
         knt = knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
         ById('AddKnights').options.length=0;
  		var o = document.createElement("option");
  		o.text = '--Choose a Knight--';
  		o.value = 0;
  		ById("AddKnights").options.add(o);
         for (k in knt){
      			if (knt[k]["Name"] !=undefined){
  	    			var o = document.createElement("option");
  	    			o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +') (' + knt[k]["Status"] +')');
  	    			o.value = knt[k]["ID"];
  	    			ById("AddKnights").options.add(o);
      			}
      	}
      },
  
    
  clickCitySelect : function (city){
  	var t = Tabs.Raid;
  	t.cityId = city['id'];
  	t.GetRaids(t.cityId);
  },
  
  checkRaids : function (){
	var t = Tabs.Raid;
	var now = unixTime();
	if(!Options.RaidRunning) return;
	if ( (now - Options.RaidReset) > 7200 ) {
		Options.RaidReset = now;
		saveOptions();
		for (g=0;g<Seed.cities.length;g++){
				t.citiesdone = "";
				setTimeout(t.resetRaids, (1500*g), Seed.cities[g][0],Seed.cities[g][1]);
		}
	}
	t.raidtimer = setTimeout(t.checkRaids, 60*60*1000); // toute les heures !
  },
  
  GetRaids : function(cityId){
  		var t = Tabs.Raid;
  		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  				
  		params.pf = 0;
  		params.ctrl = 'BotManager';
  		params.action = 'getMarches';
  		params.settings = {};
  		params.settings.cityId = cityId;
  		
  		
   		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
  		         method: "post",
  		         parameters: params,
  				 loading: true,
  				 onSuccess: function(transport){
  					var rslt = eval("(" + transport.responseText + ")");
  					
                        if (rslt.ok) {
                        	t.rslt = rslt;
  							t.paint();
  							unsafeWindow.cityinfo_army();
  							setTimeout(unsafeWindow.update_seed_ajax, 250);
  						}
  				 },
  		 });
  },

  resetRaids : function(cityId,cityName){
  		var t = Tabs.Raid;
  		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  		  		
  		params.pf = 0;
  		params.ctrl = 'BotManager';
  		params.action = 'resetRaidTimer';
		params.settings = {};
  		params.settings.cityId = cityId;
  		
  		
   		new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
  		         method: "post",
  		         parameters: params,
				 loading: true,
				 onSuccess: function(transport){
					var rslt = eval("(" + transport.responseText + ")");
                        if (rslt.ok) {
                          actionLog("RAID","Minuteur RAID remis a zero sur "+cityName);
			  unsafeWindow.cityinfo_army();
                            setTimeout(unsafeWindow.update_seed_ajax, 250);
                            t.citiesdone += cityName + ' ';
						}
				 },
  		 });
  },
  sendreport: function(){
	  var t = Tabs.Raid;
	  if(!Options.foodreport) return;
	  var now = new Date().getTime()/1000.0;
      now = now.toFixed(0);
      if (now < (parseInt(Options.LastReport)+(Options.MsgInterval*60*60))) return;
	
	var total = 0;
    var message = 'Raid Stats: %0A';
    message += '%0A Food Gain (for '+ Options.MsgInterval +' hour of raiding) %0A';
    for (q=1;q<=Seed.cities.length;q++){
    	var cityID = 'city' + Seed.cities[q-1][0];
    	var gain = parseInt(Seed.resources[cityID]['rec1'][0] / 3600) - Options.Foodstatus[q];
    	message+= Seed.cities[q-1][1] + ': Start: ' + addCommas(Options.Foodstatus[q]) + ' End :' + addCommas(parseInt(Seed.resources[cityID]['rec1'][0] / 3600)) + ' Gain: ';
    	message += addCommas(gain)  + '%0A';
		total += gain;
		Options.Foodstatus[q] = parseInt(Seed.resources[cityID]['rec1'][0] / 3600);
    }
	message += '%0A Total food gain : '+addCommas(total)+'%0A';
	
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.emailTo = Seed.player['name'];
    params.subject = "Raid Overview";
    params.message = message;
    params.requestType = "COMPOSED_MAIL";
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (message) {
            var rslt = eval("(" + message.responseText + ")");
            if (rslt.ok) {
            } else {
            }
        },
        onFailure: function () {
        },
    });
	
    Options.LastReport = now;
    saveOptions();
  },
  
  toggleRaidState : function (){
  	var t = Tabs.Raid;
  	if(Options.RaidRunning){
  		Options.RaidRunning = false;
  		t.raidtimer = null;
  		ById('pbRaidStart').value = 'Auto Reset = OFF';
  	} else {
  		Options.RaidRunning = true;
  		t.raidtimer = setTimeout(t.checkRaids, 5000);
  		ById('pbRaidStart').value = 'Auto Reset = ON';
  	}
  	saveOptions();
  },
  
    
  hide : function (){
   var t = Tabs.Raid;
   clearInterval(t.timerPaint);
   clearInterval(t.timerLookup);
  },

  show : function (){
   var t = Tabs.Raid;
   clearInterval(t.timerPaint);
   clearInterval(t.timerLookup);
   t.timerPaint = setInterval (t.paint,2000);
   t.timerLookup = setInterval(t.lookup, 3500);
  },
 }; 
 
 

unsafeWindow.ptGotoMap = function (x, y){
  setTimeout (function (){ 
    ById('mapXCoor').value = x;
    ById('mapYCoor').value = y;
    unsafeWindow.reCenterMapWithCoor();
    var a = ById("mod_views").getElementsByTagName("a");
    for (var b = 0; b < a.length; b++) {
        a[b].className = ""
    }
    ById('mod_views_map').className = "sel";
    ById("maparea_city").style.display = 'none';
    ById("maparea_fields").style.display = 'none';
    ById("maparea_map").style.display = 'block';
    unsafeWindow.tutorialClear()
  }, 0);
};

function clickWinBO(win,obj,evtName) {
	var evt = win.document.createEvent("MouseEvents");
	evt.initMouseEvent(evtName, true, true, win, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	return !obj.dispatchEvent(evt);
}
  function searchDOM (node, condition, maxLevel, doMult){
    var found = [];
    eval ('var compFunc = function (node) { return ('+ condition +') }');
    doOne(node, 1);
    if(!doMult){
      if (found.length==0)
        return null;
      return found[0];
    }
    return found;
    function doOne (node, curLevel){
      try {
        if (compFunc(node))
          found.push(node);
      } catch (e){
      }      
      if (!doMult && found.length>0)
        return; 
      if (++curLevel<maxLevel && node.childNodes!=undefined)
        for (var c=0; c<node.childNodes.length; c++)
          doOne (node.childNodes[c], curLevel);
    }
  }

function CwaitForElement (id, timeout, notify){
  this.check = check;
  this.end = new Date().getTime() + timeout;
  var t = this;
  this.check();
  function check(){
    if (document.getElementById (id))
      notify (true);
    else if (new Date().getTime() > t.end)
      notify (false);
    else
      setTimeout (t.check, 250);
  }
}


function saveAttackOptions (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('AttackOptions_'+serverID, JSON2.stringify(AttackOptions));}, 0);
}

function readAttackOptions (){
  var serverID = getServerId();
  s = GM_getValue ('AttackOptions_'+serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          AttackOptions[k][kk] = opts[k][kk];
      else
        AttackOptions[k] = opts[k];
    }
  }
}
/*******************   KOC Map interface ****************/
// 0:bog, 10:grassland, 11:lake, 20:woods, 30:hills, 40:mountain, 50:plain, 51:city / barb, 53:misted city
function CMapAjax (){
  this.normalize = normalize;  
  this.request = request;

  function request (left, top, width, notify){    
    var left = parseInt(left / 5) * 5;
    var top = parseInt(top / 5) * 5;
    var width = parseInt((width+4) / 5) * 5;
    
    var blockString = generateBlockList(left, top, width);
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.blocks = blockString;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchMapTiles.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        notify(left, top, width, rslt);
      },
      onFailure: function (rslt) {
        notify(left, top, width, rslt);
      }
    });
    function generateBlockList (left, top, width) {
      var width5 = parseInt(width / 5);
      var bl = [];
      for (x=0; x<width5; x++){
        var xx = left + (x*5);
        if (xx > 745)
          xx -= 750;
        for (y=0; y<width5; y++){
          var yy = top + (y*5);
          if (yy > 745)
            yy -= 750;
          bl.push ('bl_'+ xx +'_bt_'+ yy);
        }
      }
      return bl.join(",");
    }
  }
 
  function normalize  (x){
    if ( x >= 750)
      x -= 750;
    else if (x < 0)
      x += 750;
    return parseInt (x/5) * 5;
  }
} 
 

 
function addScript (scriptText){
	var scr = document.createElement('script');   
	scr.innerHTML = scriptText;
	document.body.appendChild(scr);
}
addScript ('uwuwuwFunc = function (text){ eval (text);  }');  

var CalterUwFunc = function (funcName, findReplace) {
  var t = this;
  this.isEnabled = false;
  this.isAvailable = isAvailable;
  this.setEnable = setEnable;
  this.funcOld = null;  
  this.funcNew = null;
  try {
    var x = funcName.split('.');
    var f = unsafeWindow;
    for (var i=0; i<x.length; i++)
      f = f[x[i]];
    ft = f.toString();
    this.funcOld = f;
    var rt = ft.replace ('function '+ funcName, 'function');
    for (var i=0; i<findReplace.length; i++){
      x = rt.replace(findReplace[i][0], findReplace[i][1]);
      if (x == rt)  // if not found
        return;
      rt = x;
    }
    this.funcNew = rt;
  } catch (err) {
  }
      
  function setEnable (tf){
    if (t.funcNew == null)
      return;
    if (t.isEnabled != tf){
      if (tf){
unsafeWindow.uwuwuwFunc(funcName +' = '+ t.funcNew);
      	t.isEnabled = true;
      } else {
      var x = funcName.split('.');
      var f = unsafeWindow;
      for (var i=0; i<x.length-1; i++)
        f = f[x[i]];
      f[x[x.length-1]] = this.funcOld;
        t.isEnabled = false;
      }
    }
  }
  function isAvailable (){
    if (t.funcNew == null)
      return false;
    return true;
  }
};

function distance (d, f, c, e) {
  var a = 750;
  var g = a / 2;
  var b = Math.abs(c - d);
  if (b > g)
    b = a - b;
  var h = Math.abs(e - f);
  if (h > g)
    h = a - h;
  return Math.round(100 * Math.sqrt(b * b + h * h)) / 100;
};

function setTabStyle (e, selected){
  if (selected){
    e.className = 'matTabSel';
  } else {
    e.className = 'matTabNotSel';
  }
}
function clickedTab2 (e){
  who2 = e.target.id.substring(3);
  newObj2 = myBO[who2];
   if (myBO[currentName2]==undefined) {
       currentName2 = 'Attaque';
    }
  currentObj2 = myBO[currentName2];
  if (currentName2 != who2){
    setTabStyle (document.getElementById ('ab'+currentName2), false);
    setTabStyle (document.getElementById ('ab'+who2), true);
    if (currentObj2){
      currentObj2.hide ();
      currentObj2.getContent().style.display = 'none';
    }
    currentName2 = who2;
    Options.currentTab2 = currentName2;
    cont = newObj2.getContent();
    newObj2.getContent().style.display = 'block';
  }
  newObj2.show();
}

function mouseMainTab (me){   // right-click on main button resets window location
  if (me.button == 2){
    var c = getClientCoords (ById('main_engagement_tabs'));
    mainPop.setLocation ({x: c.x+4, y: c.y+c.height});
  }
}

function eventHideShow (){
  if (mainPop.toggleHide(mainPop)){
    tabManager.showTab();
    Options.pbWinIsOpen = true;
  } else {
    tabManager.hideTab();
    Options.pbWinIsOpen = false;
  }
  saveOptions();
}

function hideMe (){
  mainPop.show (false);
  tabManager.hideTab();
  Options.pbWinIsOpen = false;
  saveOptions();
}

function showMe (){
  mainPop.show (true);
  tabManager.showTab();
  Options.pbWinIsOpen = true;
  saveOptions();
}


function mouseMainTab2 (me){
  if (me.button == 2){
    var c = getClientCoords (ById('main_engagement_tabs'));
    mainPop2.setLocation ({x: c.x+4, y: c.y+c.height});
  }
}

function eventHideShow2 (){
  if (mainPop2.toggleHide(mainPop2)){
    if (myBO[currentName2]==undefined) {
         currentName2 = 'Attaque';
    }
    myBO[currentName2].show();
    Options.ptWin2IsOpen = true;
  } else {
   if (myBO[currentName2]==undefined) {
       currentName2 = 'Attaque';
    }
    myBO[currentName2].hide();
    Options.ptWin2IsOpen = false;
  }
  saveOptions();
}

function reloadKOC (){
  var serverId = getServerId();
  if(serverId == '??') window.location.reload(true);
  var goto = window.location.protocol+'//apps.facebook.com/kingdomsofcamelot/?s='+serverId;
  if(document.URL.match(/standalone=1/i)){
 	goto = window.location.protocol+'//www.kabam.com/kingdoms-of-camelot/play?s='+serverId;
  }
  var t = '<FORM target="_top" action="'+ goto +'" method=post><INPUT id=xxpbButReload type=submit value=RELOAD><INPUT type=hidden name=s value="'+ serverId +'"</form>';
  var e = document.createElement ('div');
  e.innerHTML = t;
  document.body.appendChild (e);
  setTimeout (function (){ById('xxpbButReload').click();}, 0);
}

function getResearchLevels () {
	for (var t=1; t < 17; t++) {
		if (t != 7) {
			researchLevels[t] = {};
			researchLevels[t].Id = t;
			researchLevels[t].Name = unsafeWindow.techcost['tch'+t][0].replace (/&#39;/img, '\'');
			researchLevels[t].Level = parseInt(Seed.tech['tch'+t]);
			researchLevels[t].NextLevelETA = 0;
		}
	}
	var q;
	var now = unixTime();
	for(var i=0; i<Cities.numCities; i++) { // each city
		var cityID = 'city'+ Cities.cities[i].id;
		q = Seed.queue_tch[cityID];
		if (q[0] != undefined)
			researchLevels[parseInt(q[0][0])].NextLevelETA = parseInt(q[0][3]) - now;
	}
}

function getTroopDefTrainEstimates (cityID){
	var b = Seed.buildings[cityID];
	city.numBarracks = 0;
	city.maxBarracks = 0;
	city.totLevelsBarracks = 0;
	city.blacksmithLevel = 0;
	city.stableLevel = 0;
	city.workshopLevel = 0;
	city.wallLevel = 0;
	for (var j=1; j<33; j++){
		if (b['pos'+j]) {
			var bname = parseIntNan(b['pos'+j][0]);
			var blvl = parseIntNan(b['pos'+j][1]);
			if (bname==13) {
				city.numBarracks++;
				city.totLevelsBarracks += parseInt(blvl);
				if (blvl>city.maxBarracks) city.maxBarracks=blvl;
			}
			if (bname==16)
				city.blacksmithLevel = blvl;
			if (bname==15)
				city.workshopLevel = blvl;
			if (bname==17)
				city.stableLevel = blvl;
			if (bname==19)
				city.wallLevel = blvl;
		}
	}

	var now = unixTime();
	city.marshallCombatScore = 0;
	var s = Seed.knights[cityID];
	if (s) {
		s = s["knt" + Seed.leaders[cityID].combatKnightId];
		if (s){
			city.marshallCombatScore = s.combat;
			if (s.combatBoostExpireUnixtime > now)
				city.marshallCombatScore *= 1.25;
		}
	}
	city.foremanBasePoliticsScore = 0;
	var s = Seed.knights[cityID];
	if (s) {
		s = s["knt" + Seed.leaders[cityID].politicsKnightId];
		if (s) {
			city.foremanBasePoliticsScore = s.politics;
	 	     if (s.politicsBoostExpireUnixtime > now)
				city.foremanBasePoliticsScore *= 1.25;
	 }
	}

	city.loggingLevel = parseInt(Seed.tech["tch2"]);
	city.geometryLevel = parseInt(Seed.tech["tch5"]);
	city.eagleEyesLevel = parseInt(Seed.tech["tch6"]);
	city.poisonedEdgeLevel = parseInt(Seed.tech["tch8"]);
	city.metalAlloysLevel = parseInt(Seed.tech["tch9"]);
	city.featherweightPowderLevel = parseInt(Seed.tech["tch10"]);
	city.alloyHorseshoesLevel = parseInt(Seed.tech["tch12"]);
	city.fletchingLevel = parseInt(Seed.tech["tch13"]);
	city.giantsStrengthLevel = parseInt(Seed.tech["tch16"]);
	var bm = city.numBarracks + 0.1 * (city.totLevelsBarracks - city.numBarracks);
	var mf = city.marshallCombatScore/200;
	var gf = city.geometryLevel/10;
	var sf = city.stableLevel/10;
	var wf = city.blacksmithLevel/10;
	var isf = bm * (1+mf+gf);
	var csf = bm * (1+mf+gf+sf);
	var ssf = bm * (1+mf+gf+sf+wf);
	var pf = city.foremanBasePoliticsScore/200;
	var gsf = city.giantsStrengthLevel/10;
	var dsf = 1+pf+gsf;
	var h=uW.cm.ThroneController.effectBonus(77);
	var boost=(1+(h/100));

	city.Troop1Time = ((city.maxBarracks > 0)?((50/boost)/isf):0);
	city.Troop2Time = city.Troop1Time/2;
	city.Troop3Time = ((city.maxBarracks > 1 && city.eagleEyesLevel > 0)?((100/boost)/isf):0);
	city.Troop4Time = ((city.maxBarracks > 1 && city.poisonedEdgeLevel > 0)?((150/boost)/isf):0);
	city.Troop5Time = ((city.maxBarracks > 2 && city.workshopLevel > 0 && city.metalAlloysLevel > 0)?((225/boost)/isf):0);
	city.Troop6Time = ((city.maxBarracks > 3 && city.fletchingLevel > 0)?((350/boost)/isf):0);
	city.Troop7Time = ((city.maxBarracks > 4 && city.stableLevel > 0 && city.alloyHorseshoesLevel > 0)?((500/boost)/csf):0);
	city.Troop8Time = ((city.maxBarracks > 6 && city.workshopLevel > 4 && city.stableLevel > 4 && city.alloyHorseshoesLevel > 4)?((1500/boost)/csf):0);
	city.Troop9Time = ((city.maxBarracks > 5 && city.stableLevel > 0 && city.blacksmithLevel > 2 && city.featherweightPowderLevel > 0)?((1000/boost)/ssf):0);
	city.Troop10Time = ((city.maxBarracks > 7 && city.stableLevel > 1 && city.blacksmithLevel > 4 && city.geometryLevel > 4 && city.fletchingLevel > 5)?((3000/boost)/ssf):0);
	city.Troop11Time = ((city.maxBarracks > 8 && city.workshopLevel > 4 && city.stableLevel > 2 && city.blacksmithLevel > 6 && city.metalAlloysLevel > 7 && city.geometryLevel > 6)?((4500/boost)/ssf):0);
	city.Troop12Time = ((city.maxBarracks > 9 && city.stableLevel > 1 && city.blacksmithLevel > 8 && city.geometryLevel > 9 && city.fletchingLevel > 9)?((6000/boost)/ssf):0);
	// Ce n'est pas bon - les temps estim�s sur les d�fenses remparts
	city.Def53Time = ((city.wallLevel > 5 && city.blacksmithLevel > 5 && city.fletchingLevel > 4)?(180/dsf):0);
	city.Def55Time = ((city.wallLevel > 7 && city.blacksmithLevel > 7 && city.fletchingLevel > 6 && city.geometryLevel > 6)?(135/dsf):0);
	city.Def60Time = ((city.wallLevel > 3 && city.blacksmithLevel > 3 && city.poisonedEdgeLevel > 1)?(90/dsf):0);
	city.Def61Time = ((city.wallLevel > 0 && city.metalAlloysLevel > 0)?(30/dsf):0);
	city.Def62Time = ((city.wallLevel > 1 && city.blacksmithLevel > 1 && city.loggingLevel > 1)?(60/dsf):0);
}

function setCities(){
	var il = unsafeWindow.itemlist;
	for (var i=1101; i < 1115; i++)
		crestname[i] = il['i'+i].name
  getResearchLevels();
  Cities.numCities = Seed.cities.length;
  Cities.cities = [];
  Cities.byID = {};
  for (i=0; i<Cities.numCities; i++){
    city = {};
    city.idx = i;
    city.id = parseInt(Seed.cities[i][0]);
    city.name = Seed.cities[i][1];
    city.x = parseInt(Seed.cities[i][2]);
    city.y = parseInt(Seed.cities[i][3]);
    city.tileId = parseInt(Seed.cities[i][5]);
    city.provId = parseInt(Seed.cities[i][4]);
    getTroopDefTrainEstimates('city'+ city.id);
    Cities.cities[i] = city;
    Cities.byID[Seed.cities[i][0]] = city;
  }
}

function officerId2String (oid){
  if (oid==null)
    return '';
  else if (oid==3) 	
    return unsafeWindow.allianceOfficerTypeMapping[3];
  else if (oid==2)
    return unsafeWindow.allianceOfficerTypeMapping[2];
  else if (oid==1)
    return unsafeWindow.allianceOfficerTypeMapping[1];
  else if (oid==4)
      return unsafeWindow.allianceOfficerTypeMapping[4];
 return '';
}

/************************ Gold Collector ************************/
var CollectGold = {
  timer : null,
  lastCollect : {},
      
  init : function (){
    var t = CollectGold;
    for (var c=0; c<Cities.numCities; c++)
      t.lastCollect['c'+ Cities.cities[c].id] = 0;
    if (Options.pbGoldEnable)
      t.setEnable (true);
  },
  
  setEnable : function (tf){
    var t = CollectGold;
    clearTimeout (t.timer);
    if (tf)
      t.tick();
  },

  colCityName : null,
  colHappy : 0,  
  tick : function (){
    var t = CollectGold;
    for (var c=0; c<Cities.numCities; c++){
      var city = Cities.cities[c];
      var happy = Seed.citystats['city'+ city.id].pop[2];
      var since = unixTime() - t.lastCollect['c'+city.id];
      if (happy>=Options.pbGoldHappy && since>15*60){
        t.lastCollect['c'+city.id] = unixTime();
        t.colCityName = city.name;
        t.colHappy = happy;
        t.ajaxCollectGold (city, t.e_ajaxDone);
        break;
      }
    }
    t.timer = setTimeout (t.tick, 60000);    
  },

  e_ajaxDone : function (rslt){
    var t = CollectGold;
  },
 
  ajaxCollectGold : function (city, notify){
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = city.id;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/levyGold.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (notify)  
          notify (rslt);
      },
      onFailure: function (rslt) {
        if (notify)  
          notify (rslt);
      }
    });
  },
}


var gmtClock = {
  span : null,
  timer : null,
  
  init : function (){
     var t = gmtClock;

    t.setEnable (Options.gmtClock);
  },

  setEnable : function (tf){
    var t = gmtClock;
    clearInterval (t.timer);
    if (Options.gmtClock){
      t.timer = setInterval (t.everySecond, 2000);
          t.span = document.createElement ('span');
          t.span.style.fontWeight = 'bold';
          ById('kochead_time').style.display='none';
          ById('kochead_time').parentNode.appendChild (t.span);
    } else {
      if (t.span!=null) t.span.innerHTML = '';
      ById('kochead_time').style.display='';
      
    }
  },    
  everySecond : function (){
    var t = gmtClock;
    var now = new Date();  
    now.setTime(now.getTime() + (now.getTimezoneOffset()*60000));
    t.span.innerHTML = ' '+ now.toLocaleFormat('%H:%M:%S') +'';
  },
}

/************************ Refresh Every X minutes ************************/
var RefreshEvery  = {
  timer : null,
  PaintTimer : null,
  NextRefresh : 0,
  box : null,
  target : null,
  
  init : function (){
    var t = RefreshEvery;
	t.creatediv();
	if (Options.pbEveryMins < 1)
        Options.pbEveryMins = 1;
    RefreshEvery.setEnable (Options.pbEveryEnable);
  },
  
  creatediv : function(){
    var t = RefreshEvery;
	t.target = ById('comm_tabs');
	if(t.target == null){
		setTimeout(t.creatediv, 2000);
		return;
	}
	t.box = document.createElement('div');
	t.target.appendChild(t.box);
  },
  
  setEnable : function (tf){
    var t = RefreshEvery;
    clearTimeout (t.timer);
    if (tf) {
      //t.timer = setTimeout (t.doit, Options.pbEveryMins*60000);
      t.NextRefresh = unixTime() + (Options.pbEveryMins*60); 
      t.timer = setTimeout (t.Paint, 5000);
    } else {
        //t.PaintTimer = null;
		t.timer = null;
		t.NextRefresh = 0;
		t.box.innerHTML = '<BR><FONT color=white><B>&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' (' + getServerId() +')</b></font>';
	}
  },
  
  doit : function (){
    reloadKOC();
  },
  
  setTimer : function (){
    var t = RefreshEvery;
    clearTimeout (t.timer);
    if (Options.pbEveryMins < 1) Options.pbEveryMins = 1;
    RefreshEvery.setEnable (Options.pbEveryEnable);
  },
  
  Paint : function(){
     var t = RefreshEvery;
	 if(t.timer == null) return;
     now = unixTime();
     var text = '';
     var Left = parseInt(t.NextRefresh - now);
     if ( Left < 0){
		Left = 0;
		t.doit();
	 }
     if ( Left < 60) text += '<BR>&nbsp;&nbsp;&nbsp;&nbsp;<span id=BOTaref><FONT color=white><span id=BOTaref>Actualisation</span> dans </font><FONT color=red><B><span id=BOTaTim>'+ timestr(Left) +'</span></b></font></div>';
     else text += '<BR>&nbsp;&nbsp;&nbsp;&nbsp;<FONT color=white><span id=BOTaref>Actualisation</span> dans <B><span id=BOTaTim>'+ timestr(Left) +'</span></b></font></div>';
    
	 t.box.innerHTML = text;
	 
	ById('BOTaref').addEventListener ('click', t.doit, false);
	ById('BOTaTim').addEventListener ('click', function() { t.setEnable(true); }, false);
     t.timer = setTimeout (t.Paint, 5000);
  },
}

var FairieKiller  = {
  saveFunc : null,
  init : function (tf){
    FairieKiller.saveFunc = unsafeWindow.Modal.showModalUEP;
    FairieKiller.setEnable (tf);
  },
  setEnable : function (tf){
    if (tf)
      unsafeWindow.Modal.showModalUEP = eval ('function FairieKiller (a,b,c) {logit("Blocked Faire popup");}');
    else
      unsafeWindow.Modal.showModalUEP = FairieKiller.saveFunc;
  },
}


function KOCnotFound(secs){
  var div;
  var countdownTimer = null;
  var endSecs = (new Date().getTime()/1000) + secs;
    
  div = document.createElement('div');
  div.innerHTML = '<DIV style="font-size:18px; background-color:#a00; color:#fff"><CENTER><BR>La boite a d&eacute;tect&eacute;e que KOC n\'est pas charg&eacute;<BR>\
      Actualisation dans <SPAN id=pbwdsecs></span><BR><INPUT id=pbwdcan type=submit value="Annuler Actualisation"><BR><BR></div>';
  document.body.insertBefore (div, document.body.firstChild);
  ById('pbwdcan').addEventListener('click', cancel, false);
  countdown();
      
  function countdown (){
    var secsLeft = endSecs - (new Date().getTime()/1000);
    ById('pbwdsecs').innerHTML = timestr(secsLeft);
    if (secsLeft < 0)
      reloadKOC();
    countdownTimer = setTimeout (countdown, 1000);
  }
  function cancel (){
    clearTimeout (countdownTimer);
    document.body.removeChild (div);
  }
}

var WideScreen = {
  chatIsRight : false,
  useWideMap : false,
  rail : null,
  
  init : function (){
    t = WideScreen;
    if (GlobalOptions.pbWideScreen){
      t.rail = searchDOM (ById('mod_maparea'), 'node.className=="maparea_rrail"', 10);
      GM_addStyle ('.modalCurtain {width:760px !important} .mod_comm_mmb{z-index:0 !important}');  
      try {
        ById('progressBar').parentNode.removeChild(ById('progressBar'));
        ById('crossPromoBarContainer').parentNode.removeChild(ById('crossPromoBarContainer'));
      } catch (e) {
      }
    }
  },
        
  setChatOnRight : function (tf){
    t = WideScreen;
    if (tf == t.chatIsRight || !GlobalOptions.pbWideScreen)
      return;
    if (tf){
      var chat = ById('kocmain_bottom').childNodes[1];
      if (!chat || chat.className!='mod_comm')
        setTimeout (function (){t.setChatOnRight(tf)}, 1000);
      chat.style.top = '-624px';
      chat.style.left = '760px';
      chat.style.height = '720px';
      chat.style.background = 'url("'+ CHAT_BG_IMAGE +'")';
      ById('mod_comm_list1').style.height = '580px';
      ById('mod_comm_list2').style.height = '580px';
    } else {
      var chat = ById('kocmain_bottom').childNodes[1];
      chat.style.top = '0px';
      chat.style.left = '0px';
      chat.style.height = '';
      chat.style.background = '';
      ById('mod_comm_list1').style.height = '287px';
      ById('mod_comm_list2').style.height = '287px';
    }
    t.chatIsRight = tf;
  },
  
  useWideMap : function (tf) {
  	t = WideScreen;
  	if (tf == t.useWideMap || !GlobalOptions.pbWideScreen)
  		return;
  	if (tf){
      t.rail.style.display = 'none';
      ById('mapwindow').style.height = "436px";
      ById('mapwindow').style.width = "1220px";
      ById('mapwindow').style.zIndex = "50";
  	} else {
      t.rail.style.display = 'block';
      ById('mapwindow').style.height = "439px";
      ById('mapwindow').style.width = "760px";
      ById('mapwindow').style.zIndex = "";
  	}
  },
}

function DoUnsafeWindow(func, execute_by_embed) {
	if(this.isChrome || execute_by_embed) {
		var scr=document.createElement('script');
		scr.innerHTML=func;
		document.body.appendChild(scr);
	} else {
		try {  
			eval("unsafeWindow."+func);
		} catch (error) {
			logit("A javascript error has occurred when executing a function via DoUnsafeWindow. Error description: "+error.description);
		}
	}
}	
function GetDisplayName(){
	var DisplayName = ById('topnavDisplayName');
	if(DisplayName){
		DisplayName = DisplayName.innerHTML;
	}else{
		DisplayName = null;
	}
	return DisplayName;
}
var ChatPane = {
  timer:null,

  init : function(){
    var t = ChatPane;
    if(Options.HelpRequest || Options.ChatRules || Options.DeleteRequest){
     t.timer=setInterval(t.HandleChatPane, 2500);
    }
  },
  
  HandleChatPane : function() {
	var DisplayName = GetDisplayName();

	var AllianceChatBox=ById('mod_comm_list2');

	if(AllianceChatBox){
		var chatPosts = document.evaluate(".//div[contains(@class,'chatwrap')]", AllianceChatBox, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
		
		if(chatPosts){
			for (var i = 0; i < chatPosts.snapshotLength; i++) {
				thisPost = chatPosts.snapshotItem(i);
				if(Options.HelpRequest){
					
					var postAuthor = document.evaluate('.//*[contains(@class,"nm")]', thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
					if(postAuthor.snapshotItem(0)){
						var postAuthorName = postAuthor.snapshotItem(0).innerHTML;
				
						if(postAuthorName != DisplayName){
							
							var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );  
							if(helpAllianceLinks){
								for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
									thisLink = helpAllianceLinks.snapshotItem(j);
									var alreadyClicked = thisLink.getAttribute("clicked");
									if(!alreadyClicked){
										thisLink.setAttribute('clicked', 'true');
										var myregexp = /(claimAllianceChatHelp\(.*\);)/;
										var match = myregexp.exec(thisLink.getAttribute("onclick"));
										
										if (match != null) {
											onclickCode = match[0];
											if(true){
												DoUnsafeWindow(onclickCode);
											}
										}
									}
								}
							}
						}
					}
				}
				if(Options.ChatRules){
				 var myregexp1 = /gles du Chat/i;
				 if (thisPost.innerHTML.match(myregexp1)) {
				   thisPost.parentNode.removeChild(thisPost);
				 }
				}
				if(Options.DeleteRequest){
					var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
					if(helpAllianceLinks){
						for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
							thisLink = helpAllianceLinks.snapshotItem(j);
							thisLink.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(thisLink.parentNode.parentNode.parentNode.parentNode);
						}
					}
					var myregexp1 = /Tu es l'aide/i;
					var myregexp2 = /Le projet de /i;
					var myregexp3 = /n'a pas besoin d\'aide./i;
					var myregexp4 = /le maximum d\'aide/i;
					if (thisPost.innerHTML.match(myregexp1) || thisPost.innerHTML.match(myregexp2) || thisPost.innerHTML.match(myregexp3) || thisPost.innerHTML.match(myregexp4)) {
						thisPost.parentNode.removeChild(thisPost);
					}
					var myregexp1 = /You are # [1-5] of 5 to help/i;
					var myregexp2 = /\'s Kingdom does not need help\./i;
					var myregexp3 = /\'s project has already been completed\./i;
					var myregexp4 = /\'s project has received the maximum amount of help\./i;
					var myregexp5 = /You already helped with (.*?)\'s project\./i;
					if (thisPost.innerHTML.match(myregexp1) || thisPost.innerHTML.match(myregexp2) || thisPost.innerHTML.match(myregexp3) || thisPost.innerHTML.match(myregexp4) || thisPost.innerHTML.match(myregexp5)) {
						thisPost.parentNode.removeChild(thisPost);
					}
				}
			}	
		}	
	}
  },

}

String.prototype.StripQuotes = function() {
	return this.replace(/"/g,'');
}

function entier_1dec (nombre){
	if (parseInt(nombre*10)!=0){
		return parseInt(nombre*10)/10;
	} else {
	return nombre;
	}	
}

function DrawLevelIcons() {
	var maptileRe = /modal_maptile.([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)/;
	var mapwindow=ById('mapwindow');
	if(!mapwindow) return;
	var levelIcons=ById('LevelIcons');
	if(levelIcons) return;

	var ss=document.evaluate(".//a[contains(@class,'slot')]",mapwindow,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
	var lvRe=/_([0-9]+)/;
	var idDone=false;
	for(var s=0; s<ss.snapshotLength; s++) {
		var a=ss.snapshotItem(s);
		var onclick=a.getAttribute('onclick');
		var owner='';
				if(onclick) {
					var onclickM=maptileRe.exec(onclick);
					if(onclickM && onclickM[6]!='"null"') {
						var might=onclickM[7].StripQuotes();
						var alliance=onclickM[15].StripQuotes();
						var dip=getDiplomacy(alliance);
						owner=" "+onclickM[6].StripQuotes();
					}
				}
				var m=lvRe.exec(a.className);
				if(!m) continue;
				var sp=a.getElementsByTagName('span');
				if(sp.length==0) continue;
		
				if(!idDone) { a.id='levelIcons'; idDone=true; }
				sp[0].style.color='#cc0';
				
				if (alliance == 'null' && onclickM[12]=='"city"') sp[0].style.color='#33CCFF';
				if (dip == 'hostile' && onclickM[12]=='"city"') sp[0].style.color='#FF0000';
				if (onclickM[12]!='"city"' &&  onclickM[6]!='"null"') sp[0].style.color='#FF9900';
				if (onclickM[12]!='"city"' &&  onclickM[5]=='"null"' && onclickM[6]=='"null"' && onclickM[7]=='"null"' && onclickM[8]=='"null"' && onclickM[15]=='"null"' && onclickM[10]=='"null"') sp[0].style.color='#CC0033';
				if (onclickM && onclickM[6]!='"null"' ) sp[0].innerHTML='&nbsp;'+m[1]+owner+'<br />Puis:'+addCommas(might);
					else sp[0].innerHTML='&nbsp;'+m[1]+addCommas(owner);
	
	}

}
function CdispCityPicker (id, span, dispName, notify, selbut){
  function CcityButHandler (t){
    var that = t;
    this.clickedCityBut = clickedCityBut;
    function clickedCityBut (e){
      if (that.selected != null)
        that.selected.className = "castleBut castleButNon";
      that.city = Cities.cities[e.target.id.substr(that.prefixLen)];
      if (that.dispName)
        ById(that.id+'cname').innerHTML = that.city.name;
      e.target.className = "castleBut castleButSel";
      that.selected = e.target;
      if (that.coordBoxX){
        that.coordBoxX.value = that.city.x;
        that.coordBoxY.value = that.city.y;
        that.coordBoxX.style.backgroundColor = '#ffffff';
        that.coordBoxY.style.backgroundColor = '#ffffff';
      }
      if (that.notify != null)
        that.notify(that.city, that.city.x, that.city.y);
    }
  }

  function selectBut (idx){
    ById(this.id+'_'+idx).click();
  }

  function bindToXYboxes (eX, eY){
    function CboxHandler (t){
      var that = t;
      this.eventChange = eventChange;
      if (that.city){
        eX.value = that.city.x;
        eY.value = that.city.y;
      }
      function eventChange (){
			var xValue=that.coordBoxX.value.trim();
			var xI=/^\s*([0-9]+)[\s,]+([0-9]+)/.exec(xValue); 		
			if(xI) {
				that.coordBoxX.value=xI[1]
				that.coordBoxY.value=xI[2]
			}
        var x = parseInt(that.coordBoxX.value, 10);
        var y = parseInt(that.coordBoxY.value, 10);
        if (isNaN(x) || x<0 || x>750){
          that.coordBoxX.style.backgroundColor = '#ff8888';
          return;
        }
        if (isNaN(y) || y<0 || y>750){
          that.coordBoxY.style.backgroundColor = '#ff8888';
          return;
        }
        that.coordBoxX.style.backgroundColor = '#ffffff';
        that.coordBoxY.style.backgroundColor = '#ffffff';
        if (that.notify != null)
          that.notify (null, x, y);
      }
    }
    this.coordBoxX = eX;
    this.coordBoxY = eY;
    var bh = new CboxHandler(this);
    eX.size=2;
    eX.maxLength=10;
    eY.size=2;
    eY.maxLength=3;
    eX.addEventListener('change', bh.eventChange, false);
    eY.addEventListener('change', bh.eventChange, false);
  }

  this.selectBut = selectBut;
  this.bindToXYboxes = bindToXYboxes;
  this.coordBoxX = null;
  this.coordBoxY = null;
  this.id = id;
  this.dispName = dispName;
  this.prefixLen = id.length+1;
  this.notify = notify;
  this.selected = null;
  this.city = null;
  var m = '';
  for (var i=0; i<Cities.cities.length; i++)
    m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit \>';
  if (dispName)
    m += ' &nbsp; <SPAN style="display:inline-block; width:85px; font-weight:bold;" id='+ id +'cname' +'></span>';
  span.innerHTML = m;
  var handler = new CcityButHandler(this);
  for (var i=0; i<Cities.cities.length; i++)
    document.getElementById (id+'_'+i).addEventListener('click', handler.clickedCityBut, false);
  if (selbut != null)
    this.selectBut(selbut);
}

var pop = null;

function dialogRetry (errMsg, seconds, onRetry, onCancel, errCode){
  seconds = parseInt(seconds);
  if (pop == null) {
   pop = new CPopup ('BOptretry', 0, 0, 400,300, true);
  
     pop.getTopDiv().innerHTML = '<CENTER><b>Boite &agrave; outils</b></center>';
     pop.getMainDiv().innerHTML = '<CENTER><BR><FONT COLOR=#550000><B>Une erreur a &eacute;t&eacute; d&eacute;tect&eacute;e :</b></font><BR><BR><DIV id=BOparetryErrMsg></div>\
         <BR><BR><B>Nouvel essai dans <SPAN id=BOparetrySeconds></b></span> secondes ...<BR><INPUT id=BOparetryCancel type=submit value="'+uW.g_js_strings.commonstr.cancel+'" \>';
     ById('BOparetryCancel').addEventListener ('click', doCancel, false);

  }
  pop.show(true);
  pop.centerMe(mainPop.getMainDiv());
  if(errCode && unsafeWindow.g_js_strings.errorcode['err_'+errCode])
	if (document.getElementById('BOparetryErrMsg')) document.getElementById('BOparetryErrMsg').innerHTML = unsafeWindow.g_js_strings.errorcode['err_'+errCode]+"<br>"+ errCode + " > " + errMsg;
  else
	if (document.getElementById('BOparetryErrMsg')) document.getElementById('BOparetryErrMsg').innerHTML = errMsg;
  if (document.getElementById('BOparetrySeconds')) document.getElementById('BOparetrySeconds').innerHTML = seconds;
  var rTimer = setTimeout (doRetry, seconds*1000);
  countdown ();

  function countdown (){
     if (document.getElementById('BOparetrySeconds')) ById('BOparetrySeconds').innerHTML = seconds--;
    if (seconds > 0)
      cdTimer = setTimeout (countdown, 1000);
  }
  function doCancel(){
    clearTimeout (rTimer);
    clearTimeout (cdTimer);
    pop.destroy();
    onCancel ();
  }
  function doRetry (){
    clearTimeout (rTimer);
    clearTimeout (cdTimer);
    pop.show(false);
    onRetry();
  }
}

function GM_AjaxGet (url, args, notify, label){
  GM_xmlhttpRequest({
    method: "get",
    url: addUrlArgs(url, args),
    onload: function (rslt) {
      notify (rslt.responseText);
    },
    onerror: function () {
      notify (null);
    },
  });
}  

function GM_AjaxPost (url, args, notify, label){
  GM_xmlhttpRequest({
    method: "post",
    url: url,
    data: implodeUrlArgs(args),
    headers: { "Content-Type": "application/x-www-form-urlencoded", 'X-Requested-With': 'XMLHttpRequest', 'X-Prototype-Version': '1.6.1',
               'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' },
    onload: function (rslt) {
      notify (rslt.responseText);
    },
    onerror: function () {
      notify (null);
    },
  });
}
function AjaxRequest (url, opts){
  var headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-Prototype-Version': '1.6.1',
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  };
  var ajax = null;
  
  if (window.XMLHttpRequest)
    ajax=new XMLHttpRequest();
  else
    ajax=new ActiveXObject("Microsoft.XMLHTTP");
  
  if (opts.method==null || opts.method=='')
    method = 'GET';
  else
    method = opts.method.toUpperCase();  
    
  if (method == 'POST'){
    headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
  } else if (method == 'GET'){
    addUrlArgs (url, opts.parameters);
  }

  ajax.onreadystatechange = function(){
    if (ajax.readyState==4) {
      if (ajax.status >= 200 && ajax.status < 305)
        if (opts.onSuccess) opts.onSuccess(ajax);
      else
        if (opts.onFailure) opts.onFailure(ajax);
    } else {
      if (opts.onChange) opts.onChange (ajax);
    }
  }  
  ajax.open(method, url, true);
  for (var k in headers)
    ajax.setRequestHeader (k, headers[k]);
  if (matTypeof(opts.requestHeaders)=='object')
    for (var k in opts.requestHeaders)
      ajax.setRequestHeader (k, opts.requestHeaders[k]);
      
  if (method == 'POST'){
    var a = [];
    for (k in opts.parameters){
	  if(matTypeof(opts.parameters[k]) == 'object')
		for(var h in opts.parameters[k])
			a.push (k+'['+h+'] ='+ opts.parameters[k][h] );
	  else
        a.push (k +'='+ opts.parameters[k] );
	}
    ajax.send (a.join ('&'));
  } else               {
    ajax.send();
  }
}   
function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}

function implodeUrlArgs (obj){
  var a = [];
  for (var k in obj)
    a.push (k +'='+ encodeURI(obj[k]) );
  return a.join ('&');    
}
function addUrlArgs (url, args){
  if (!args)
    return url;
  if (url.indexOf('?') < 0)
    url += '?';
  else if (url.substr(url.length-1) != '&')
    url += '&';    
  if (matTypeof(args == 'object'))
    return url + implodeUrlArgs (args);    
  return url + args;
}
function AjaxRequest2 (url, opts){
    var headers = {
        'X-Requested-With': 'XMLHttpRequest',
        'X-Prototype-Version': '1.6.1',
        'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };
    var ajax = null;   
    if (window.XMLHttpRequest)
      ajax=new XMLHttpRequest();
    else
      ajax=new ActiveXObject("Microsoft.XMLHTTP");   
    if (opts.method==null || opts.method=='')
      method = 'GET';
    else
      method = opts.method.toUpperCase();    
    if (method == 'POST'){
        headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    } else if (method == 'GET'){
        addUrlArgs (url, opts.parameters);
    }    
    ajax.onreadystatechange = function(){
        if (ajax.readyState==4) {
            if (ajax.status >= 200 && ajax.status < 305)
            if (opts.onSuccess) opts.onSuccess(ajax);
            else
                if (opts.onFailure) opts.onFailure(ajax);
            } else {
                if (opts.onChange) opts.onChange (ajax);
            }
    }    
    ajax.open(method, url, true); 
    for (var k in headers)
      ajax.setRequestHeader (k, headers[k]);
     if (matTypeof(opts.requestHeaders)=='object')
          for (var k in opts.requestHeaders)
            ajax.setRequestHeader (k, opts.requestHeaders[k]);
    if (method == 'POST'){
        var a = [];
        for (k in opts.parameters){
              if(matTypeof(opts.parameters[k]) == 'object'){
                  for(var h in opts.parameters[k]){
                      if(matTypeof(opts.parameters[k][h]) == 'object'){
                          for(var i in opts.parameters[k][h]){
                              if(matTypeof(opts.parameters[k][h][i]) == 'object'){
                              for(var j in opts.parameters[k][h][i]){
                                  a.push (k+'['+h+']['+i+']['+j+'] ='+ opts.parameters[k][h][i][j] );
                              }
                              } else
                              	a.push (k+'['+h+']['+i+']'+' ='+ opts.parameters[k][h][i]);
                          }
                      } else
                      a.push (k+'['+h+'] ='+ opts.parameters[k][h] );
                  }
              } else
              a.push (k +'='+ opts.parameters[k] );
        }
        ajax.send (a.join ('&'));
    } else {
        ajax.send();
    }
}
function MyAjaxRequest (url, o, noRetryX){
  var opts = unsafeWindow.Object.clone(o);
  var wasSuccess = o.onSuccess;
  var wasFailure = o.onFailure;
  var retry = 0;
  var delay = 4;
  var noRetry = noRetry===true?true:false;
  opts.onSuccess = mySuccess;
  opts.onFailure = myFailure;
  new AjaxRequest(url, opts);
  return;

  function myRetry(){
    ++retry;
    if (retry>5) {
       actionLog("Erreur", "<font color=res>ERREUR REQUETE : 5 tentatives, on arrete</font>");
       return false;
       }
    new AjaxRequest(url, opts);
  
    delay = delay * 1.20;
  }
  function myFailure(){
    var o = {};
    o.ok = false;
    o.errorMsg = "AJAX Communication Failure";
    wasFailure (o);
  }
  function mySuccess (msg){
    var rslt = eval("(" + msg.responseText + ")");
    var x;
    if (window.EmulateAjaxError){
      rslt.ok = false;  
      rslt.error_code=8;
    }
    if (rslt==undefined) {
     rslt={};
     rslt.ok = false;  
     rslt.error_code=0;
     rslt.errorMsg="Response server in error !"
     //wasSuccess (rslt);
     dialogRetry (rslt.errorMsg, delay, function(){myRetry()}, function(){wasSuccess (rslt)}, rslt.error_code);
     return;
    }
    if (rslt.ok){
      if (rslt.updateSeed)
        unsafeWindow.update_seed(rslt.updateSeed);
      wasSuccess (rslt);
      return;
    }
    
    rslt.errorMsg = unsafeWindow.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null));

    if (!noRetry && (rslt.error_code==0 ||rslt.error_code==8 || rslt.error_code==1 || rslt.error_code==3)){
      actionLog("Erreur", "<font color=res>ERREUR REQUETE : "+ msg.responseText +"</font>");
      dialogRetry (inspect(rslt.errorMsg), delay, function(){myRetry()}, function(){wasSuccess (rslt)}, rslt.error_code);
    } else {
      wasSuccess (rslt);
    }
  }
}

function getDiplomacy (aid) {
  if (Seed.allianceDiplomacies == null)
    return 'neutre';
  if (Seed.allianceDiplomacies.friendly && Seed.allianceDiplomacies.friendly['a'+aid] != null)
    return 'amicale';
  if (Seed.allianceDiplomacies.hostile && Seed.allianceDiplomacies.hostile['a'+aid] != null)
    return 'hostile';
  if (aid == Seed.allianceDiplomacies.allianceId)
    return 'allie';
  return 'neutre';
};

function getMyUserId (){return parseInt([Seed.tutorial.userId]);}
function getMyAlliance (){
  if (Seed.allianceDiplomacies==null || Seed.allianceDiplomacies.allianceName==null)
    return [0, 'None'];
  else
    return [Seed.allianceDiplomacies.allianceId, Seed.allianceDiplomacies.allianceName];
}
function UniteKMG(nb) {
          if (Math.abs(nb)>1000000000)
    	    val="<span title='"+addCommas(nb)+"'>" + (nb/1000000000).toFixed(2) +" G</span>";
    	  else if (Math.abs(nb)>1000000)                               
    	   val="<span title='"+addCommas(nb)+"'>" + (nb/1000000).toFixed(2) +" M</span>";
     	  else if (nb==0)
    	   val="0";
    	  else
	   val=addCommas(nb);
    
     return val;
}
    
function getMarchInfoBOT(cityID){
  var ret = {};
  ret.marchUnits = [];
  ret.returnUnits = [];
  ret.resources = [];
  for (i=0; i<13; i++){
    ret.marchUnits[i] = 0;
    ret.returnUnits[i] = 0;
  }
  for (i=0; i<6; i++){
    ret.resources[i] = 0;
  }
  
  for (k in Seed.queue_atkp[cityID]){  
      march = Seed.queue_atkp[cityID][k];
	  if(march.marchType != 5){
		  if (typeof (march) == 'object'){
			for (ii=0; ii<13; ii++){
			  ret.marchUnits[ii] += parseInt (march['unit'+ ii +'Count']);
			  ret.returnUnits[ii] += parseInt (march['unit'+ ii +'Return']);
			}
			for (ii=1; ii<5; ii++){
			  ret.resources[ii] += parseInt (march['resource'+ ii]);
			}
			  ret.resources[0] += parseInt (march['gold']);
		  }
	  }
    }
  return ret;
}

function getMarchInfo (){
  var ret = {};
  ret.marchUnits = [];
  ret.returnUnits = [];
  ret.resources = [];
  for (i=0; i<13; i++){
    ret.marchUnits[i] = 0;
    ret.returnUnits[i] = 0;
  }
  for (i=0; i<6; i++){
    ret.resources[i] = 0;
  }
  var now = unixTime();
  for(i=0; i<Cities.numCities; i++) {   // each city
    cityID = 'city'+ Cities.cities[i].id;
    for (k in Seed.queue_atkp[cityID]){   // each march
      march = Seed.queue_atkp[cityID][k];
      if (typeof (march) == 'object'){
        for (ii=0; ii<13; ii++){
          ret.marchUnits[ii] += parseInt (march['unit'+ ii +'Count']);
          ret.returnUnits[ii] += parseInt (march['unit'+ ii +'Return']);
        }
        for (ii=1; ii<5; ii++){
          ret.resources[ii] += parseInt (march['resource'+ ii]);
        }
         ret.resources[0] += parseInt (march['gold']);
      }
    }
  }
  return ret;
}
var fortNamesShort = { 53: "Arbaletes",  55: "Trebuchet",  60: "Pieges",  61: "Chausse-trape",  62: "Palissade",}
function getCityBuilding (cityId, buildingId){
  var b = Seed.buildings['city'+cityId];
  var ret = {count:0, maxLevel:0};
  for (var i=1; i<33; i++){
    if (b['pos'+i] && b['pos'+i][0] == buildingId){
      ++ret.count;
      if (parseInt(b['pos'+i][1]) > ret.maxLevel)
        ret.maxLevel = parseInt(b['pos'+i][1]);
    }
  }
  return ret;
}
function logit (msg){
  var serverID = getServerId();
  var now = new Date();
  GM_log (serverID +' @ '+ now.toTimeString().substring (0,8) +'.' + now.getMilliseconds() +': '+  msg);
}

function readOptions(){var a=getServerId();s=GM_getValue("BOOptions_"+a);if(s!=null){opts=JSON2.parse(s);for(k in opts)Options[k]=opts[k]}}
function saveOptions(){var a=getServerId();GM_setValue("BOOptions_"+a,JSON2.stringify(Options))}
function saveLangOptions (){setTimeout (function (){GM_setValue ('LangOptions_', JSON2.stringify(LangOptions));}, 0);}
function readCrestOptions(){var a=getServerId();s=GM_getValue("CrestOptions_"+Seed.player["name"]+"_"+a);if(s!=null){opts=JSON2.parse(s);for(k in opts){if(matTypeof(opts[k])=="object")for(kk in opts[k])CrestOptions[k][kk]=opts[k][kk];else CrestOptions[k]=opts[k]}}}
function saveCrestOptions(){var a=getServerId();setTimeout(function(){GM_setValue("CrestOptions_"+Seed.player["name"]+"_"+a,JSON2.stringify(CrestOptions))},0)}
function saveColors (){var serverID = getServerId();GM_setValue('Colors', JSON2.stringify(Colors));}
function readColors (){
  var serverID = getServerId();
  s = GM_getValue ('Colors');
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts)
      Colors[k] = opts[k];
  }
}
function readCombatOptions (){
  var serverID = getServerId();
  s = GM_getValue ('CombatOptions_' + Seed.player['name'] + '_' +serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
			if (matTypeof(opts[k][kk]) == 'object')
				for (kkk in opts[k][kk])
				  CombatOptions[k][kk][kkk] = opts[k][kk][kkk];
			else
				CombatOptions[k][kk] = opts[k][kk];
      else
        CombatOptions[k] = opts[k];
    }
  }
}
function saveCombatOptions (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('CombatOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(CombatOptions));}, 0);
}
function createButton (label){
  var a=document.createElement('a');
  a.className='button20';
  a.innerHTML='<span style="color: #ff6">'+ label +'</span>';
  return a;
}
function createBlinkButton (label){
  var a=document.createElement('a');
  a.className='button20';
  a.innerHTML='<span style="color: #fff"><blink>'+ label +'</blink></span>';
  return a;
}

function AddMainTabLink(text, eventListener, mouseListener) {
  var a = createButton ("La boite &agrave; Outils");
  a.className='tab';
  a.id = 'ptBoite';
  var tabs=ById('main_engagement_tabs');
  
  if(!tabs) {
    tabs=ById('topnav_msg');
    if (tabs)
      tabs=tabs.parentNode;
  }
  if(tabs) {
   eNew2 = document.createElement('div');
   eNew2.id = 'BOAbout';
   eNew2.style.background='#5b5';
   eNew2.className='tabs_engagement';
   eNew2.style.paddingLeft='25px';
   eNew2.style.whiteSpace='nowrap';
   eNew2.style.width='735px';
   tabs.parentNode.insertBefore (eNew2, tabs);
   eNew2.innerHTML="<a id=BoBoite class='tab'  style='float:right;margin-right:20px;'><span style='color:#ff6'>Support</span></a><span style='float:right;margin-right:20px;margin-top:4px;font-size:16px;text-shadow: 1px 1px 1px #AAA; font-variant:small-caps;'><center><b>Boite &agrave; outils "+Version+" - BeWorld</b></center></span>";
    
   var e = tabs.parentNode;
    var eNew = null;
    for (var i=0; i<e.childNodes.length; i++){
      var ee = e.childNodes[i];
   
      if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' &&  ee.id!='main_engagement_tabs' &&  ee.id!='BOAbout'){
        eNew = ee;
        break;
      }
    }
    if (eNew == null){   
      eNew = document.createElement('div');
      eNew.className='tabs_engagement';
      eNew.style.background='#5a5';
      eNew.style.paddingLeft='25px';
      tabs.parentNode.insertBefore (eNew, tabs);
      eNew.id = 'gmTabs';
      eNew.style.whiteSpace='nowrap';
      eNew.style.width='735px';
    }
    if (eNew2.firstChild){
      eNew2.insertBefore (a, eNew2.firstChild);
    }else{
      eNew2.appendChild(a);
     }

      
  

   ById("BoBoite").addEventListener('click',function() {
      window.open("http://beworld.perso.sfr.fr/bao");
   }, false); 
    a.addEventListener('click',eventListener, false);
    if (mouseListener != null)
      a.addEventListener('mousedown',mouseListener, true);
      
      
     if (tabs) {
       GM_xmlhttpRequest({method:"GET",url:"http://beworld.perso.sfr.fr/bao/104299.user.js",onload:function(a){var b=/\/\/\s*@version\s+(.+)\s*\n/i.exec(a.responseText);
       var c=Version;if(b){if(b[1]>c){
       var eNewMAJ=createBlinkButton ("BAO "+b[1]+" dispo !");
       eNewMAJ.className='tab';
       eNewMAJ.id="BOUpdate";
       eNewMAJ.title="Mettez a jour votre boite a outils !";
       eNew2.insertBefore(eNewMAJ,eNew2.firstChild);
       eNewMAJ.addEventListener('click',function() {
               window.open('http://beworld.perso.sfr.fr/bao/'); //redirection sur mon site
       }, false);
       
       }}},onerror:function(a){}})
       
       
      }  
      
      
    return a;
  }
  return null;
}
function AddMainTabLink2(text, eventListener, mouseListener) {
  var b = createButton ("Statistiques");
  b.className='tab';
  b.id = 'ptBoite2';
  
  var tabs=ById('main_engagement_tabs');
  if(!tabs) {
    tabs=ById('topnav_msg');
    if (tabs)
      tabs=tabs.parentNode;
  }
  if(tabs) {
  
   var e = tabs.parentNode;
    var eNew = null;
    for (var i=0; i<e.childNodes.length; i++){
      var ee = e.childNodes[i];
   
      if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' &&  ee.id!='main_engagement_tabs' &&  ee.id!='BOAbout'){
        eNew = ee;
        break;
      }
    }
    if (eNew == null){
      eNew = document.createElement('div');
      eNew.className='tabs_engagement';
      eNew.style.background='#ca5';
      tabs.parentNode.insertBefore (eNew, tabs);
      eNew.id = 'gmTabs';
      eNew.style.whiteSpace='nowrap';
      eNew.style.width='735px';
    }
    if (eNew2.firstChild){
      eNew2.insertBefore (b, eNew2.firstChild);
    }else{
      eNew2.appendChild(b);
     }
    
    b.addEventListener('click',eventListener, false);
    if (mouseListener != null)
      b.addEventListener('mousedown',mouseListener, true);
    return b;
  }
  return null;
}

unsafeWindow.PTscout = function (x, y){
  var a=confirm("Voulez-vous envoyer un eclaireur ?");
  if (a) {
  setTimeout (function (){ 
    ById('mapXCoor').value = x;
    ById('mapYCoor').value = y;
    unsafeWindow.Modal.hideModalAll();
    unsafeWindow.reCenterMapWithCoor();
    unsafeWindow.changeview_map(ById('mod_views_map'));
	unsafeWindow.modal_attack(3,x,y);
	setTimeout (function (){ 
	  var scouter = ById('modal_attack_unit_ipt3');
	  scouter.value=1;
	  var evt = document.createEvent("KeyboardEvent");
		  if(evt.initKeyboardEvent) {
				evt.initKeyboardEvent("keyup",true,true,null,false,false,false,false,0x10,0);
		  } else {
				evt.initKeyEvent("keyup",true,true,null,false,false,false,false,0x10,0);
		  }
	  scouter.dispatchEvent(evt);
	  unsafeWindow.modal_attack_do();	
	}, 500);
   }, 0);
  }
};

function makeButton20 (label){
  var a = document.createElement('a');
  a.className = "button20 ptButton20";
  var s = document.createElement('span');
  s.innerHTML = label;
  a.appendChild (s);
  return a;
}

function strButton20 (label, tags){
  if (tags == null)
    tags = '';
  return ('<TABLE class=ptNoPad><TR><TD><A class="button20 ptButton20" '+ tags +'><SPAN>'+ label +'</span></a></td></tr></table>' );
}

function strButton14 (label, tags){
  if (tags == null)
    tags = '';
  return ('<A class="button14 ptButton20" '+ tags +'><SPAN>'+ label +'</span></a>' );
}

function cityStatusString (cs){
  if (cs==4)
    return 'Vacances';
  if (cs==3)
    return 'Paix';
  if (cs==2)
    return 'Protection Debutant';
  return 'Normal';
}    

function sendChat (msg){
  document.getElementById ("mod_comm_input").value = msg;
  unsafeWindow.Chat.sendChat ();
}
function doDefTrain (cityId, siege, unitId, num, notify){
  var time = unsafeWindow.modal_walls_traintime(unitId, num);
  var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  params.cid = cityId;
  params.type = unitId;
  params.quant = num;
  params.items = siege;
  new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fortify.php" + unsafeWindow.g_ajaxsuffix, {
      method: "post",
      parameters: params,
      onSuccess: function (rslt) {
        if (rslt.ok) {
          unsafeWindow.seed.queue_fort["city" + cityId].push([unitId, num, rslt.initTS, parseInt(rslt.initTS) + time, 0, time, rslt.fortifyId]);
          if (notify != null)
            setTimeout (function (){notify(null);}, 500);
        } else {
          if (notify != null)
            setTimeout (function (){notify(rslt.errorMsg);}, 500);
        }
      },
      onFailure: function () {
        if (notify != null)
          notify(rslt.errorMsg);
      },
  });
}
function doTrain (cityId, tut, gam, unitId, num, notify){
  var time = unsafeWindow.modal_barracks_traintime(unitId, num);
  if(tut==36){time=parseInt(time*0.7)}else{if(tut==37){time=parseInt(time*0.5)}else{if(tut==38){time=parseInt(time*0.3)}}}
  var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
  params.cid = cityId;
  params.type = unitId;
  params.quant = num;
  params.items = tut;
  params.gambleId = gam;
  new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/train.php" + unsafeWindow.g_ajaxsuffix, {
    method: "post",
    parameters: params,
    onSuccess: function(rslt) {
      if (rslt.ok) {
       var resourceFactors=[],resourceLost;
       if(gam!=null){
         time=rslt.timeNeeded;
	}
        for(var i=1;i<5;i++){
        if(rslt.gamble){
         resourceFactors.push(rslt.gamble[i.toString()]);
        }else{
        resourceFactors.push(1);
        }
        resourceLost=parseInt(unsafeWindow.unitcost["unt"+unitId][i])*3600*parseInt(num);resourceLost=resourceLost*resourceFactors[i-1];
        unsafeWindow.seed.resources["city"+cityId]["rec"+i][0]=parseInt(unsafeWindow.seed.resources["city"+cityId]["rec"+i][0])-resourceLost;
       }
       unsafeWindow.seed.citystats["city"+cityId].gold[0]=parseInt(unsafeWindow.seed.citystats["city"+cityId].gold[0])-parseInt(unsafeWindow.unitcost["unt"+unitId][5])*parseInt(num);
       unsafeWindow.seed.citystats["city"+cityId].pop[0]=parseInt(unsafeWindow.seed.citystats["city"+cityId].pop[0])-parseInt(unsafeWindow.unitcost["unt"+unitId][6])*parseInt(num);
       unsafeWindow.seed.queue_unt["city"+cityId].push([unitId,num,rslt.initTS,parseInt(rslt.initTS)+time,0,time,null]);
       
       if (tut!=0) unsafeWindow.seed.items["i"+tut]=Number(unsafeWindow.seed.items["i"+tut])-1;
	if(rslt.updateSeed) { unsafeWindow.update_seed(rslt.updateSeed) }
       if (notify != null)
          setTimeout (function (){notify(null);}, 100);
      } else {
        if (notify != null){
          setTimeout (function (){notify(rslt.errorMsg);}, 100);
        }
      }
    },
    onFailure: function(rslt) {
      if (notify != null)
        notify(rslt.errorMsg);
    }
  });
}

function getAbsoluteOffsets (e){
  ret = {left:0, top:0};
  while (e.offsetParent){
    if (e.style.position == 'absolute')
      break;
    ret.left += e.offsetLeft;
    ret.top += e.offsetTop;
    e = e.offsetParent;
  }      
  return ret;  
}

function getClientCoords(e){
  if (e==null)
    return {x:null, y:null, width:null, height:null};
  var x=0, y=0;
  ret = {x:0, y:0, width:e.clientWidth, height:e.clientHeight};
  while (e.offsetParent != null){
    ret.x += e.offsetLeft;
    ret.y += e.offsetTop;
    e = e.offsetParent;
  }
  return ret;
}

function htmlTitleLine (msg){
  return '<TABLE width=100% cellspacing=0><TR><TD style="padding:0px" width=50%><HR></td><TD style="padding:0px">[ '+ msg +' ]</td><TD style="padding:0px" width=50%><HR></td></tr></table>';  
}

function CPopup (prefix, x, y, width, height, enableDrag, onClose) {
  var pop = WinManager.get(prefix);
  if (pop){
    pop.show (false);
    return pop;
  }
  this.BASE_ZINDEX = 123457;
  this.stmaxh = height;
  this.stmaxw = width;
  this.show = show;
  this.toggleHide = toggleHide;
  this.getTopDiv = getTopDiv;
  this.getMainTopDiv = getMainTopDiv;
  this.getMainDiv = getMainDiv;
  this.getLayer = getLayer;
  this.setLayer = setLayer;
  this.setEnableDrag = setEnableDrag;
  this.getLocation = getLocation;
  this.setLocation = setLocation;
  this.focusMe = focusMe;
  this.isShown = isShown;
  this.unfocusMe = unfocusMe;
  this.centerMe = centerMe;
  this.destroy = destroy;
  this.autoHeight = autoHeight;
  this.autoWidth = autoWidth;
  this.div = document.createElement('div');
  this.prefix = prefix;
  this.onClose = onClose;  
  var t = this;
  this.div.className = 'BOCPopup '+ prefix +'_CPopup';
  this.div.id = prefix +'_outer';
  this.div.style.background = "#fff";
  this.div.style.zIndex = this.BASE_ZINDEX;
  this.div.style.display = 'none';
  if (Options.BOTransparence) this.div.style.opacity = '0.9';
  this.div.style.width = width + 'px';
  this.div.style.height = height + 'px';
  this.div.style.maxHeight = height + 'px';
  this.div.style.overflowY = 'hidden';
  this.div.style.position = "absolute";
  this.div.style.top = y +'px';
  this.div.style.left = x + 'px';
  this.div.style.width = width + 'px';
  this.div.style.maxWidth = width + 'px';
  topClass = 'BOCPopupTop '+ prefix +'_CPopupTop';
  var m = '<TABLE cellspacing=0 width=100% height=100%><TR id="'+ prefix +'_bar" class="'+ topClass +'"><TD width=99% valign=bottom><SPAN id="'+ prefix +'_top"></span></td>\
      <TD id='+ prefix +'_X align=right valign=middle onmouseover="this.style.cursor=\'pointer\'" style="color:#fff; background:#333; font-weight:bold; font-size:14px; padding:0px 5px">X</td></tr>\
      <TR><TD height=100% valign=top class="BOCPopMain '+ prefix +'_CPopMain" colspan=2 id="'+ prefix +'_main"></td></tr></table>';
  document.body.appendChild(this.div);
  this.div.innerHTML = m;
  ById(prefix+'_X').addEventListener ('click', e_XClose, false);
  this.dragger = new CWinDrag (ById(prefix+'_bar'), this.div, enableDrag);
  
  this.div.addEventListener ('mousedown', e_divClicked, false);
  WinManager.add(prefix, this);
  
  function e_divClicked (){
    t.focusMe();
  }  
  function e_XClose (){
    t.show(false);
    if (t.onClose != null)
      t.onClose();
  }
  function autoHeight (onoff){
     if (onoff) {
       t.div.style.height = '';  
       t.div.style.maxHeight ='';
    } else{
       t.div.style.height = t.stmaxh;
       t.div.style.maxHeight = t.stmaxh;
       }
  }
  function autoWidth (onoff){
         if (onoff) {
           t.div.style.width = '';  
           t.div.style.maxWidth ='';
        } else{
           t.div.style.width = t.stmaxw;
           t.div.style.maxWidth = t.stmaxw;
           }
  }
  function focusMe (){
    t.setLayer(5);
    for (k in unsafeWindow.cpopupWins){
      if (k != t.prefix)
        unsafeWindow.cpopupWins[k].unfocusMe();
    }
  }
  function unfocusMe (){
    t.setLayer(-5);
  }
  function getLocation (){
    return {x: parseInt(this.div.style.left), y: parseInt(this.div.style.top)};
  }
  function setLocation (loc){
    t.div.style.left = loc.x +'px';
    t.div.style.top = loc.y +'px';
  }
  function destroy (){
    document.body.removeChild(t.div);
    WinManager.delete (t.prefix);
  }
  function centerMe (parent){
    if (parent == null){
      var coords = getClientCoords(document.body);
    } else
      var coords = getClientCoords(parent);
    var x = ((coords.width - parseInt(t.div.style.width)) / 2) + coords.x;
    var y = ((coords.height - parseInt(t.div.style.height)) / 2) + coords.y;
    if (x<0)
      x = 0;
    if (y<0)
      y = 0;
    t.div.style.left = x +'px';
    t.div.style.top = y +'px';
  }
  function setEnableDrag (tf){
    t.dragger.setEnable(tf);
  }
  function setLayer(zi){
    t.div.style.zIndex = ''+ (this.BASE_ZINDEX + zi);
  }
  function getLayer(){
    return parseInt(t.div.style.zIndex) - this.BASE_ZINDEX;
  }
  function getTopDiv(){
    return ById(this.prefix+'_top');
  }
  function getMainDiv(){
    return ById(this.prefix+'_main');
  }
  function getMainTopDiv(){
  	return ById(this.prefix+'_top');
  }
  function isShown (){
    return t.div.style.display == 'block';
  }
  function show(tf){
    if (tf){
      t.div.style.display = 'block';
      t.focusMe ();
    } else {
      t.div.style.display = 'none';
    }
    return tf;
  }
  function toggleHide(t){
    if (t.div.style.display == 'block') {
      return t.show (false);
    } else {
      return t.show (true);
    }
  }
}


function CWinDrag (clickableElement, movingDiv, enabled) {
  var t=this;
  this.setEnable = setEnable;
  this.setBoundRect = setBoundRect;
  this.debug = debug;
  this.dispEvent = dispEvent;
  this.lastX = null;
  this.lastY = null;
  this.enabled = true;
  this.moving = false;
  this.theDiv = movingDiv;
  this.body = document.body;
  this.ce = clickableElement;
  this.moveHandler = new CeventMove(this).handler;
  this.outHandler = new CeventOut(this).handler;
  this.upHandler = new CeventUp(this).handler;
  this.downHandler = new CeventDown(this).handler;
  this.clickableRect = null;
  this.boundRect = null;
  this.bounds = null;
  this.enabled = false;
  if (enabled == null)
    enabled = true;
  this.setEnable (enabled);

  function setBoundRect (b){  
    this.boundRect = boundRect;
    this.bounds = null;
  }

  function setEnable (enable){
    if (enable == t.enabled)
      return;
    if (enable){
      clickableElement.addEventListener('mousedown',  t.downHandler, false);
      t.body.addEventListener('mouseup', t.upHandler, false);
    } else {
      clickableElement.removeEventListener('mousedown', t.downHandler, false);
      t.body.removeEventListener('mouseup', t.upHandler, false);
    }
    t.enabled = enable;
  }

  function CeventDown (that){
    this.handler = handler;
    var t = that;
    function handler (me){
      if (t.bounds == null){
        t.clickableRect = getClientCoords(clickableElement);
        t.bodyRect = getClientCoords(document.body);
        if (t.boundRect == null)
          t.boundRect = t.clickableRect;
        t.bounds = {top:10-t.clickableRect.height, bot:t.bodyRect.height-25, left:40-t.clickableRect.width, right:t.bodyRect.width-25};
      }
      if (me.button==0 && t.enabled){
        t.body.addEventListener('mousemove', t.moveHandler, true);
        t.body.addEventListener('mouseout', t.outHandler, true);
        t.lastX = me.clientX;
        t.lastY = me.clientY;
        t.moving = true;
      }
    }
  }

  function CeventUp  (that){
    this.handler = handler;
    var t = that;
    function handler (me){
      if (me.button==0 && t.moving)
        _doneMoving(t);
    }
  }

  function _doneMoving (t){
    t.body.removeEventListener('mousemove', t.moveHandler, true);
    t.body.removeEventListener('mouseout', t.outHandler, true);
    t.moving = false;
  }

  function CeventOut  (that){
    this.handler = handler;
    var t = that;
    function handler (me){
      if (me.button==0){
        t.moveHandler (me);
      }
    }
  }

  function CeventMove (that){
    this.handler = handler;
    var t = that;
    function handler (me){
      if (t.enabled && !t.wentOut){
        var newTop = parseInt(t.theDiv.style.top) + me.clientY - t.lastY;
        var newLeft = parseInt(t.theDiv.style.left) + me.clientX - t.lastX;
        if (newTop < t.bounds.top){     // if out-of-bounds...
          newTop = t.bounds.top;
          _doneMoving(t);
        } else if (newLeft < t.bounds.left){
          newLeft = t.bounds.left;
          _doneMoving(t);
        } else if (newLeft > t.bounds.right){
          newLeft = t.bounds.right;
          _doneMoving(t);
        } else if (newTop > t.bounds.bot){
          newTop = t.bounds.bot;
          _doneMoving(t);
        }
        t.theDiv.style.top = newTop + 'px';
        t.theDiv.style.left = newLeft + 'px';
        t.lastX = me.clientX;
        t.lastY = me.clientY;
      }
    }
  }

  function debug  (msg, e){
    logit ("*************** "+ msg +" ****************");
    logit ('clientWidth, Height: '+ e.clientWidth +','+ e.clientHeight);
    logit ('offsetLeft, Top, Width, Height (parent): '+ e.offsetLeft +','+ e.offsetTop +','+ e.offsetWidth +','+ e.offsetHeight +' ('+ e.offsetParent +')');
    logit ('scrollLeft, Top, Width, Height: '+ e.scrollLeft +','+ e.scrollTop +','+ e.scrollWidth +','+ e.scrollHeight);
  }

  function dispEvent (msg, me){
    logit (msg + ' Button:'+ me.button +' Screen:'+ me.screenX +','+ me.screenY +' client:'+  me.clientX +','+ me.clientY +' rTarget: '+ me.relatedTarget);
  }
}


var WinManager = {
  wins : {},   
  didHide : [],

  get : function (prefix){
    var t = WinManager;
    return t.wins[prefix];
  },
  
  add : function (prefix, pop){
    var t = WinManager;
    t.wins[prefix] = pop;
    if (unsafeWindow.cpopupWins == null)
      unsafeWindow.cpopupWins = {};
    unsafeWindow.cpopupWins[prefix] = pop;
  },
  
  hideAll : function (){
    var t = WinManager;
    t.didHide = [];
    for (k in t.wins){
      if (t.wins[k].isShown()){
        t.didHide.push (t.wins[k]);
        t.wins[k].show (false);
      }
    }
  },
  restoreAll : function (){
    var t = WinManager;
    for (var i=0; i<t.didHide.length; i++)
      t.didHide[i].show (true);
  },
  
  delete : function (prefix){
    var t = WinManager;
    delete t.wins[prefix];
    delete unsafeWindow.cpopupWins[prefix];
  }    
}

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { 
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
}

String.prototype.entityTrans = {  '&agrave;':'\\u00e0', '&eacute;':'\\u00e9', '&':'&amp;', '<':'&lt;',  '>':'&gt;',  '\"':'&quot;', '\'':'&#039', '<':'\\u003c', '/':'\\/', '\\':'\\\\', '\"':'\\\"','{':'&#123;','}':'&#125;'};

String.prototype.htmlEntities = function() {
  var ret = this.toString();
  for (k in this.entityTrans)
     ret  = ret.split(k).join(this.entityTrans[k]);
  return ret;
}
String.prototype.htmlSpecialChars = function() {
  var ret = this.toString();
  for (k in this.entityTrans)
     ret  = ret.split(k).join(this.entityTrans[k]);
  return ret;
}
String.prototype.htmlSpecialCharsDecode = function() {
  var ret = this.toString();
  for (k in this.entityTrans)
     ret = ret.split(this.entityTrans[k]).join(k);
  return ret;
}
String.prototype.stripTags = function(){ 
  return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
}

String.prototype.capitalize = function(){ 
  return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}

function objectName (o){
  var s = o.toString();
  return s.substr(7,s.length-8);
}

function matTypeof (v){
  if (v == undefined)
    return 'undefined';
  if (typeof (v) == 'object'){
    if (!v)
      return 'null';
    else if (v.constructor.toString().indexOf("Array")>=0 && typeof(v.splice)=='function')
      return 'array';
    else return 'object';
  }
  return typeof (v);
}

function addCommasInt(n){
  nStr = parseInt(n) + '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1' + ',' + '$2');
  }
  return nStr;
}

function addCommas(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function htmlSelector(a,b,c){m=[];m.push("<SELECT");if(c){m.push(" ");m.push(c)}for(k in a){m.push("><OPTION ");if(k==b)m.push("SELECTED ");m.push('value="');m.push(k);m.push('">');m.push(a[k]);m.push("</option>")}m.push("</select>");return m.join("")}
function unixTime(){ return parseInt (new Date().getTime() / 1000) + unsafeWindow.g_timeoff;}
function timestrShort(a){a=parseInt(a);if(a>86400){var b=[];a/=3600;b.push(parseInt(a/24));b.push("d ");b.push(parseInt(a%24));b.push("h ");return b.join("")}else return timestr(a)}
function timestr(a,b){a=parseInt(a);var c=[];var d=a;if(d<61)return d+"s";if(d>86400){c.push(parseInt(d/86400));c.push("d ");d%=86400}if(d>3600||a>3600){c.push(parseInt(d/3600));c.push("h ");d%=3600}c.push(parseInt(d/60));c.push("m");if(b||a<=3600){c.push(" ");c.push(d%60);c.push("s")}return c.join("")}
function getMyAlliance(){if(Seed.allianceDiplomacies==null||Seed.allianceDiplomacies.allianceName==null)return[0,"None"];else return[Seed.allianceDiplomacies.allianceId,Seed.allianceDiplomacies.allianceName]}
function addCommasWhole(a){a+="";x=a.split(".");x1=x[0];x2=x.length>1?"."+x[1]:"";var b=/(\d+)(\d{3})/;while(b.test(x1)){x1=x1.replace(b,"$1"+","+"$2")}return x1}
function CmatSimpleSound (playerUrl, container, attrs, onLoad, flashVars) {
  var self = this;
  this.player = null;
  this.volume = 100;
  this.isLoaded = false;
  this.onSwfLoaded = null;
  var div = document.createElement ('div');
  this.onSwfLoaded = onLoad;
  if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
    div.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="'+playerUrl+'"><param name="quality" value="high"></object>';
    this.player = div.getElementsByTagName('object')[0];
  } else {
    div.innerHTML = '<embed src="'+playerUrl+'"  bgcolor="#eeeeee" allowfullscreen=false FlashVars="'+ flashVars +'" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" ></embed>';
    this.player = div.getElementsByTagName('embed')[0].wrappedJSObject;
  }
  if (container)
    container.appendChild (div);
  else
    document.body.appendChild (div);
  for (k in attrs)
    this.player.setAttribute(k, attrs[k]);
       
  this.setVolume = function (chanNum, vol){
    if (!self.isLoaded)
      return;
    self.player.jsSetVolume (chanNum, vol);
    volume = vol;
  }
  
  this.load = function (chanNum, url, bStream, bAutoplay, bUsePolicyFile){ 
    self.player.jsLoad (chanNum, url, bStream, bAutoplay, bUsePolicyFile);
  }
  
  this.play = function (chanNum, position){
    if (self.player.jsPlay)  self.player.jsPlay (chanNum, position);
  }
    
  this.stop = function (chanNum){
   if (!self.isLoaded)
      return;
    self.player.jsStop (chanNum);
  }
    
  this.getStatus = function (chanNum){   
    return self.player.jsGetStatus (chanNum);
  }
  
  this.debugFunc = function (msg){ 
  }
      
  this.swfDebug = function (msg){ 
    self.debugFunc('SWF: '+ msg);
  }
  this.swfLoaded = function (){ 
    self.isLoaded = true;
    self.debugFunc ('playerIsReady');
    if (self.onSwfLoaded)
      self.onSwfLoaded();
  }
  this.swfPlayComplete = function (chanNum){ 
  }
  this.swfLoadComplete = function (chanNum, isError){ 
  }
}

function SliderBar (container, width, height, value, classPrefix, margin){
  var self = this;
  this.listener = null;
  if (value==null)
    value = 0;
  if (!margin)
    margin = parseInt(width*.05);
  this.value = value;
  if (width<20) width=20;
  if (height<5) height=5;
  if (classPrefix == null){
    classPrefix = 'slider';
    var noClass = true;
  }      
  var sliderHeight = parseInt(height/2);  
  var sliderTop = parseInt(height/4);
  this.sliderWidth = width - (margin*2);
    
  this.div = document.createElement ('div');  
  this.div.style.height = height +'px';
  this.div.style.width = width +'px';
  this.div.className = classPrefix +'Cont';
  if (noClass)
    this.div.style.backgroundColor='#ddd';
  
  this.slider = document.createElement ('div');
  this.slider.setAttribute ('style', 'position:relative;');
  this.slider.style.height = sliderHeight + 'px'
  this.slider.style.top = sliderTop + 'px';
  this.slider.style.width = this.sliderWidth +'px';
  this.slider.style.left = margin +'px';
  this.slider.className = classPrefix +'Bar';
  this.slider.draggable = true;
  if (noClass)
    this.slider.style.backgroundColor='#fff';
  
  this.sliderL = document.createElement ('div');
  this.sliderL.setAttribute ('style', 'width:100px; height:100%; position:relative; ');
  this.sliderL.className = classPrefix +'Part';
  this.sliderL.draggable = true;
  if (noClass)
    this.sliderL.style.backgroundColor='#0c0';
  
  this.knob = document.createElement ('div');
  this.knob.setAttribute ('style', 'width:3px; position:relative; left:0px; background-color:#222');
  this.knob.style.height = height +'px';
  this.knob.style.top = (0-sliderTop) +'px';
  this.knob.className = classPrefix +'Knob';
  this.knob.draggable = true;
  this.slider.appendChild(this.sliderL);
  this.sliderL.appendChild (this.knob);
  this.div.appendChild (this.slider);
  container.appendChild (this.div);
  this.div.addEventListener('mousedown',  mouseDown, false);

  this.getValue = function (){
    return self.value;
  }

  this.setValue = function (val){
    var relX = (val * self.sliderWidth);
    self.sliderL.style.width = relX + 'px';
    self.knob.style.left =  relX + 'px';
    self.value = val;
    if (self.listener)
      self.listener(self.value);
  }
  
  this.setChangeListener = function (listener){
    self.listener = listener;
  }

  function moveKnob (me){
    var relX = me.clientX - self.divLeft;
    if (relX < 0)
      relX = 0;
    if (relX > self.sliderWidth)
      relX = self.sliderWidth;
    self.knob.style.left = (relX - (self.knob.clientWidth/2) ) +'px';
    self.sliderL.style.width = relX + 'px';
    self.value =  relX / self.sliderWidth;   
    if (self.listener)
      self.listener(self.value);
  }
  function doneMoving (){
    self.div.removeEventListener('mousemove', mouseMove, true);
    document.removeEventListener('mouseup', mouseUp, true);
  }  
  function mouseUp (me){
    moveKnob (me);
    doneMoving();
  }
  
  function mouseDown(me){
    var e = self.slider;
    self.divLeft = 0;
    while (e.offsetParent){
      self.divLeft += e.offsetLeft;
      e = e.offsetParent;
    }
    moveKnob (me);
    document.addEventListener('mouseup',  mouseUp, true);
    self.div.addEventListener('mousemove',  mouseMove, true);
  }
  function mouseMove(me){
    moveKnob (me);
  }
}
function AddSubTabLink(text, eventListener, id) {
  var a = createYellowButton (text,'botbutton');
  a.className='tab';
  var tabs=ById('main_engagement_tabs');
  if(!tabs) {
    tabs=ById('topnav_msg');
    if (tabs)
      tabs=tabs.parentNode;
  }
  if (tabs) {
    var e = tabs.parentNode;
    var gmTabs = null;
    for (var i=0; i<e.childNodes.length; i++){
      var ee = e.childNodes[i];
      if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' && ee.id!='main_engagement_tabs' &&  ee.id!='BOAbout'){
        gmTabs = ee;
        break;
      }
    }
    if (gmTabs == null){
      gmTabs = document.createElement('div');
      gmTabs.className='tabs_engagement';
      gmTabs.style.background='#ca5';
      tabs.parentNode.insertBefore (gmTabs, tabs);
      gmTabs.style.whiteSpace='nowrap';
      gmTabs.style.width='735px';
      gmTabs.lang = 'en_PB';
    }
    gmTabs.appendChild(a);
    a.addEventListener('click',eventListener, false);
    if (id != null)
      a.id = id;
    return a;
  }
  return null;
}
function AddTowerTab(text, eventListener, id) {
  var a = createRedButton (text,'botbutton');
  a.className='tab';
  a.style.cssFloat="right";
  a.style.marginRight="20px";
  a.title="Attention !!! "+uW.g_js_strings.modaltitles.impatks+" !";
  var tabs=ById('main_engagement_tabs');
  if(!tabs) {
    tabs=ById('topnav_msg');
    if (tabs)
      tabs=tabs.parentNode;
  }
  if (tabs) {
    var e = tabs.parentNode;
    var gmTabs = null;
    for (var i=0; i<e.childNodes.length; i++){
      var ee = e.childNodes[i];
      if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' && ee.id!='main_engagement_tabs' &&  ee.id!='BOAbout'){
        gmTabs = ee;
        break;
      }
    }
    if (gmTabs == null){
      gmTabs = document.createElement('div');
      gmTabs.className='tabs_engagement';
      gmTabs.style.background='#ca5';
      tabs.parentNode.insertBefore (gmTabs, tabs);
      gmTabs.style.whiteSpace='nowrap';
      gmTabs.style.width='735px';
      gmTabs.lang = 'en_PB';
    }
    gmTabs.appendChild(a);
    a.addEventListener('click',eventListener, false);
    if (id != null)
      a.id = id;
    return a;
  }
  return null;
}

function estETA(dist, unit, cityID, typemarche) {
 var ret={ETA:0,etaStr:'N/D',friendETA:0,friendEtaStr:'N/D'};    
 if (dist <= 0) return ret;
 var troop_type = unit;
 var horse=0;
 if(troop_type>6) horse=1;
 var troop_speed=parseInt(unsafeWindow.unitstats["unt"+troop_type][3])*(1+0.1*parseInt(Seed.tech.tch11));
 if (horse){
               troop_speed=troop_speed*(1+0.05*parseInt(Seed.tech.tch12))
 } 
 var Speed = troop_speed;
 
 
  var throne67=uW.cm.ThroneController.effectBonus(67);
  var throne68,throne69,throne70,throne71,throne72;throne68=throne69=throne70=throne71=throne72=0;
  if(typemarche==4){
   throne68=uW.cm.ThroneController.effectBonus(68) // attaque
  }else{
   if(typemarche==3){ //eclaireur
    throne72=uW.cm.ThroneController.effectBonus(72)
   }else{
    if(typemarche==2){ //renforce
     throne69=uW.cm.ThroneController.effectBonus(69)
    }else{
     if(typemarche==5){ // reassign
      throne71=uW.cm.ThroneController.effectBonus(71)
     }else{
      if(typemarche==1){ // transport
       throne70=uW.cm.ThroneController.effectBonus(70)}}}}}
       
  var throneBoost=throne67+throne68+throne69+throne70+throne71+throne72;
  
 Speed=Speed*(1+(throneBoost*0.01));
 
 var gi=unsafeWindow.cm.guardianModalModel.getMarchBonus();
 var multiplier=1+(gi*0.01);
 Speed=Speed*multiplier;
 var gSpeed = 0;
 var estSec;
 if (Speed>0) {
  gSpeed = Speed/6000;
  estSec = Math.ceil(parseFloat(dist)/gSpeed);
 }

 var e=1;
 if (ById("BOitem_55")) {
  var l_elem=ById("BOitem_55");
  if(l_elem&&l_elem.checked>0){ e=0.75;     }
 }
 if (ById("BOitem_57")) {
  var l_elem=ById("BOitem_57");
  if(l_elem&&l_elem.checked){   e=0.5;   }
 }
 ret.ETA = (parseInt((estSec*e+''))+30); 
 if(Seed.playerEffects.returnExpire>unsafeWindow.unixtime()){
  ret.ETA=parseInt(ret.ETA*0.5);
 }
 ret.etaStr = timestr (ret.ETA,1);
 if (cityID!=0) {
  var building = getCityBuilding (cityID, 18);
  if (building) {
   fSpeed = Speed * (1 + parseInt(building.maxLevel)/2);
   gSpeed = fSpeed/6000;
   estSec = (dist/gSpeed).toFixed(0);
   ret.friendETA = parseInt((estSec*e+''))+30; 
   ret.friendEtaStr = timestr ((ret.friendETA+''),1);
  }
 } else {
  ret.friendETA = ret.ETA; 
  ret.friendEtaStr = timestr ((ret.friendETA+''),1);
 }
 return ret;
}

function updatebotbutton2(a,b){var c=ById(b);if(c)c.innerHTML='<span style="color: #F71F02">'+a.replace("- ON",butON).replace("- OFF",butOFF)+"</span>"}
function updatebotbutton(a,b){var c=ById(b);if(c)c.innerHTML='<span style="color: #ff6">'+a.replace("- ON",butON).replace("- OFF",butOFF)+"</span>"}
function createRedButton(a,b){var c=document.createElement("a");c.style.display='none';c.className="button20";c.id=b;c.innerHTML='<span style="color: #ff6">'+a+"</span>";return c}
function createYellowButton(a,b){
 var c=document.createElement("a");c.className="button20";c.id=b;
 c.innerHTML='<span style="color: #ff6">'+a.replace("- ON",butON).replace("- OFF",butOFF)+'</span>';
 return c
}
var DeleteReports = {
    deleting : false,
    deletes1 : new Array(),
    deletes0 : new Array(),
    timer:null,
    init : function(){
		var t = DeleteReports;
		clearInterval(t.timer);
		if(!t.deleting && (Options.DeleteMsg || Options.DeleteMsgs0 || Options.DeleteMsgs4 || Options.DeleteMsgs1 || Options.DeleteMsgs2 || Options.DeleteMsgs3)){
		 if (parseIntNan(Options.DeleteTimerMinute)<5) Options.DeleteTimerMinute=5;
		 t.timer = setInterval(t.startdeletereports, Options.DeleteTimerMinute*60000);
		}
    },
	
    startdeletereports : function(){
		var t = DeleteReports;
		t.deletes1 = new Array();
		t.deletes0 = new Array();
	  	if(!t.deleting && (Options.DeleteMsg || Options.DeleteMsgs0 || Options.DeleteMsgs4 || Options.DeleteMsgs1 || Options.DeleteMsgs2 || Options.DeleteMsgs3)){
	  		t.deleting = true;
	  		t.fetchreport(0, t.checkreports);
	  	}
    },
    
    fetchreport : function(pageNo, callback){
		var t = DeleteReports;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		if(pageNo > 1)
			params.pageNo = pageNo;
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				callback(rslt,pageNo);
			},
				onFailure: function () {
				callback();
			},
		});
    },
	
    checkreports : function(rslt, pageNo){
		var t = DeleteReports;
		actionLog("Rapport", "Verification des rapports page "+(pageNo+1)+"/"+rslt.totalPages+" a supprimer.");
		if(!rslt.ok){
			return;
		}
		if(rslt.arReports.length < 1){
			return;
		}
		var reports = rslt.arReports;
		var totalPages = rslt.totalPages;
	
		for(k in reports){
			if(Options.DeleteMsg){
				if((reports[k].marchType==9 || reports[k].marchType==4) && reports[k].side0PlayerId==0 && reports[k].side0TileType > 50)
					t.deletes1.push(k.substr(2));
				else if(reports[k].marchType==1 && t.isMyself(reports[k].side1PlayerId))
					t.deletes1.push(k.substr(2));
			}
			if (Options.DeleteMsgs0){
				if(reports[k].marchType==1 && !t.isMyself(reports[k].side1PlayerId)) {
					t.deletes0.push(k.substr(2));
				}
			}
			if (Options.DeleteMsgs1){
				if(reports[k].marchType==4 && (reports[k].side0TileType <= 50)&& reports[k].side0PlayerId==0)
					t.deletes1.push(k.substr(2));
			}
			if (Options.DeleteMsgs2){
				if(reports[k].side0TileType==54)
					t.deletes1.push(k.substr(2));
			}
			if (Options.DeleteMsgs3){
				if(reports[k].side0TileType==51 && reports[k].marchType==2 && t.isMyself(reports[k].side0PlayerId))
					t.deletes1.push(k.substr(2));
			}
			if (Options.DeleteMsgs4){
				if(reports[k].side0TileType==51 && reports[k].marchType==3)
					t.deletes1.push(k.substr(2));
			}
		}
		if ((pageNo+1)==totalPages || parseInt(pageNo+1)>10) {
		
		if(t.deletes1.length > 0 || t.deletes0.length > 0){
			t.deleteCheckedReports(t.deletes1, t.deletes0);
		} else {
			actionLog("Rapport", "Aucune suppression de rapport necessaire");
			t.deleting = false;
			return;
		}
		
		} else {
		  t.fetchreport(pageNo+1, t.checkreports);
		}
    },
    deleteCheckedReports : function(deletes1, deletes0){
		var t = DeleteReports;
		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
		params.s1rids = deletes1.join(",");
		params.s0rids = deletes0.join(",");
		params.cityrids = '';
		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
			method: "post",
			parameters: params,
			onSuccess: function (rslt) {
				if(rslt.ok){
					Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length) - parseInt(deletes0.length);
					actionLog("Rapport", "Suppression de "+(parseInt(deletes1.length)+parseInt(deletes0.length))+" Rapports automatiquement");
				} else {
				  actionLog("Rapport", "Erreur Suppression des rapports : "+ rslt.msg);
				}
				t.deleting = false;
			},
			onFailure: function () {
			 actionLog("Rapport", "Erreur Suppression des rapports : "+ rslt.msg);
			 t.deleting = false;
			},
		});
    },	
    isMyself: function(userID){
		var t = DeleteReports;
		if(!Seed.players["u"+userID])
			return false;
		if(Seed.players["u"+userID].n == Seed.player.name)
			return true;
		else
			return false;
		return false;
    },
}


var tabManager = {
  tabList : {},      
  currentTab : null,
  init : function (mainDiv){
    var t = tabManager;
    var sorter = [];
    for (k in Tabs){
      if (!Tabs[k].tabDisabled){  
        t.tabList[k] = {};
        t.tabList[k].name = k;
        t.tabList[k].obj = Tabs[k];
        if (Tabs[k].tabLabel != null)
          t.tabList[k].label = Tabs[k].tabLabel;
        else
          t.tabList[k].label = k;
        if (Tabs[k].tabOrder != null)
          sorter.push([Tabs[k].tabOrder, t.tabList[k]]);
        else
          sorter.push([1000, t.tabList[k]]);
        t.tabList[k].div = document.createElement('div');
      }
    }

    sorter.sort (function (a,b){return a[0]-b[0]});
    var m = '<TABLE cellspacing=0 cellpadding=0><TR>';
    for (var i=0; i<sorter.length; i++){
     m += '<TD align=center class=BOTabNotSel id=pbtc'+ sorter[i][1].name +'><A><SPAN class="matTab">'+ sorter[i][1].label +'</span></a></td>';
      if (i==8) m+='</tr><tr>';
    }
    m+='</tr></table>';
    mainPop.getMainTopDiv().innerHTML = m;
    
    for (k in t.tabList) {
      if (t.tabList[k].name == Options.currentTab)
        t.currentTab =t.tabList[k] ;
      ById('pbtc'+ k).addEventListener('click', this.e_clickedTab, false);
      var div = t.tabList[k].div;
      div.style.display = 'none';
      div.style.height = '100%';
      mainDiv.appendChild(div);
      try {
        t.tabList[k].obj.init(div);
      } catch (e){
      
      }
    }
    
    if (t.currentTab == null)
      t.currentTab = sorter[0][1];    
    t.setTabStyle (document.getElementById ('pbtc'+ t.currentTab.name), true);
    t.currentTab.div.style.display = 'block';
  },
  
  hideTab : function (){
    var t = tabManager;
    t.currentTab.obj.hide();
  },
  
  showTab : function (){
    var t = tabManager;
    t.currentTab.obj.show();
  },
    
  setTabStyle : function (e, selected){
    if (selected){
      e.className = 'BOTabSel';
    } else {
      e.className = 'BOTabNotSel';
    }
  },
  e_clickedTab : function (e){
    var t = tabManager;
    newTab = t.tabList[e.target.parentNode.parentNode.id.substring(4)];
    if (t.currentTab.name != newTab.name){
      t.setTabStyle (document.getElementById ('pbtc'+ t.currentTab.name), false);
      t.setTabStyle (document.getElementById ('pbtc'+ newTab.name), true);
      t.currentTab.obj.hide ();
      t.currentTab.div.style.display = 'none';
      t.currentTab = newTab;
      newTab.div.style.display = 'block';
      Options.currentTab = newTab.name;      
    }
    newTab.obj.show();
  },
}

ptStartup ();


function readLangOptions (){
s = GM_getValue ('LangOptions_');
if (s != null){
opts = JSON2.parse (s);
for (k in opts){
if (matTypeof(opts[k]) == 'object')
for (kk in opts[k])
LangOptions[k][kk] = opts[k][kk];
else
LangOptions[k] = opts[k];
}
}
};
function matTypeof (v){
  if (v == undefined)
    return 'undefined';
  if (typeof (v) == 'object'){
    if (!v)
      return 'null';
//    else if (unsafeWindow.Object.prototype.toString.apply(v) === '[object Array]')
    else if (v.constructor.toString().indexOf("Array")>=0 && typeof(v.splice)=='function')
      return 'array';
    else return 'object';
  }
  return typeof (v);
};
/**********************************************************************************
							KOC POWER - END
			greetz fly out to jontey, Nico De Belder, Tom Chapin
				this Script was done by koc.god-like.org
**********************************************************************************/
